In this Java tutorial, you will learn how to read an integer from console input entered by user using Scanner.nextInt() method, with examples.

Read Integer from Console in Java

In Java, you can read an integer from Console using nextInt() on Scanner.

In this tutorial, we will learn how to read an integer from user input via console.

First of all, to read anything from the console, you have to create a Scanner with System standard input of the computer.

Then use nextInt() method on the scanner object to read an integer from the console.

Examples

1. Read integer from console and print it

In the following Java program, we read an integer from console input and print it back to the console.

Example.java

</>
Copy
import java.util.Scanner;

public class Example {
	public static void main(String[] args) {
		// Create a scanner to read bytes from standard input
		Scanner scanner = new Scanner(System.in);
		
		System.out.print("Enter a number : ");
		
		// Read integer from console entered via standard input
		int num = scanner.nextInt();
		
		System.out.println("You entered the number : "+ num);
		
		// Close scanner
		scanner.close();
	}
}

Run this program. When it is run, it asks user to enter a number.