English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Read Integer from Console in Java

To read an integer from the console, use the Scanner class.

Scanner myInput = new Scanner(System.in);

This method allows the user to add an integernextInt().

System.out.print("Enter first integer: ");
int a = myInput.nextInt();

Similarly, enter another input in the new variable.

System.out.print("Enter second integer: ");
Int b = myInput.nextInt();

Let's see the complete example.

Example

import java.util.Scanner;
public class Demo {
   public static void main(String args[]) {
      Scanner myInput = new Scanner(System.in);
      int a;
      int b;
      int sum;
      System.out.print("Enter first integer: ");
      a = myInput.nextInt();
      System.out.print("Enter second integer: ");
      b = myInput.nextInt();
      sum = a + b;
      System.out.printf("Sum = %d\n", sum);
   }
}

The following two integer values were added from the console.

5
10

After adding values and running the program, the following output can be seen.

Enter first integer: 5
Enter second integer: 10
Sum = 15