Please note, this is a STATIC archive of website www.w3schools.com from 05 May 2020, cach3.com does not collect or store any user information, there is no "phishing" involved.
THE WORLD'S LARGEST WEB DEVELOPER SITE

Java How To Add Two Numbers


Add Two Numbers

Learn how to add 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
Run example »

Add Two Numbers with User Input

Learn how to add two numbers with user input:

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
  }
} 
Run example »