Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Add Two Numbers

Add Two Numbers

Discover how to perform addition with two numbers in Java.

Example

int x = 5;
int y = 6;
int sum = x + y;
System.out.println(sum); // Print the sum of x + y
 

Add Two Numbers with User Input

Learn how to perform addition with two numbers provided by the user in Java.

Example

import java.util.Scanner; // Import the Scanner class
class MyClass {
  public static void main(String[] args) {
    int x, y, sum;
    Scanner myObj = new Scanner(System.in); // Create a Scanner object
    System.out.println("Type a number:");
    x = myObj.nextInt(); // Read user input
    System.out.println("Type another number:");
    y = myObj.nextInt(); // Read user input
    sum = x + y;  // Calculate the sum of x + y
    System.out.println("Sum is: " + sum); // Print the sum
  }
}