In Java, you can read an integer entered at the console using a Scanner connected to System.in and the nextInt() method. This tutorial explains the basic syntax, shows a complete example, and covers invalid input and safe integer validation.
Read an Integer from Console Using Scanner in Java
The java.util.Scanner class provides methods for reading values from standard input. When a Java program is run from a terminal or an IDE console, System.in represents the standard input stream, which normally receives input typed by the user.
To read an integer, create a Scanner object for System.in, and then call nextInt() on that scanner.
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
The first statement creates a scanner that reads from standard input. The second statement waits for the next input token that can be interpreted as a Java int and stores it in number.
Import Scanner Before Reading Console Input
Scanner belongs to the java.util package. Therefore, add the following import statement at the beginning of the Java source file when you use the class by its simple name.
import java.util.Scanner;
1. Read an 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
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.
)
When the user enters an integer, scanner.nextInt() reads that integer and returns it. The returned value is assigned to the num variable.
)
How Scanner.nextInt() Reads Integer Input
nextInt() reads the next complete input token and attempts to interpret it as an integer. For example, if the user enters 25, the method returns the integer value 25. It does not return the text string "25".
Because nextInt() reads tokens rather than an entire line, whitespace such as spaces and line breaks normally separates one input value from the next.
Reading More Than One Integer from Console
You can call nextInt() multiple times when the program needs more than one integer. Each call reads the next integer token from the input.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first integer: ");
int first = scanner.nextInt();
System.out.print("Enter second integer: ");
int second = scanner.nextInt();
System.out.println("First integer: " + first);
System.out.println("Second integer: " + second);
scanner.close();
}
}
For example, if the user enters 10 and 20, the two calls to nextInt() store those values separately.
Enter first integer: 10
Enter second integer: 20
First integer: 10
Second integer: 20
InputMismatchException When Console Input Is Not an Integer
If the next input token cannot be interpreted as an integer, nextInt() throws an InputMismatchException.
For example, entering characters together with the number, such as 52ds, is not valid integer input for nextInt().
Enter a number : 52ds
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Unknown Source)
at java.base/java.util.Scanner.next(Unknown Source)
at java.base/java.util.Scanner.nextInt(Unknown Source)
at java.base/java.util.Scanner.nextInt(Unknown Source)
at JavaTutorial.main(JavaTutorial.java:10)
This happens because the program asks Scanner for an integer, but the next token in the input is not a valid integer representation.
Check Console Input with hasNextInt() Before Reading
If console input may contain an invalid value, you can call hasNextInt() before nextInt(). The method returns true when the next token can be read as an int.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
if (scanner.hasNextInt()) {
int number = scanner.nextInt();
System.out.println("You entered: " + number);
} else {
System.out.println("The entered value is not a valid integer.");
}
scanner.close();
}
}
This approach lets the program detect invalid input instead of immediately calling nextInt() on a token that cannot be converted to an integer.
Read an Integer from a Full Console Line
Another approach is to read the input as text using nextLine() and then convert that text with Integer.parseInt(). This is useful when the program is designed around line-based input rather than token-based input.
import java.util.Scanner;
public class Example {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
String input = scanner.nextLine();
int number = Integer.parseInt(input);
System.out.println("You entered: " + number);
scanner.close();
}
}
Here, nextLine() returns a String. Integer.parseInt() then converts that string to an int. If the string is not a valid integer representation, Integer.parseInt() throws a NumberFormatException.
nextInt() and nextLine() When Reading Mixed Console Input
A common issue appears when nextInt() is followed immediately by nextLine(). The integer method reads the integer token but does not consume the line separator entered after it. As a result, the following nextLine() may read the remaining empty part of that line.
If you need to read an integer and then a complete line of text, consume the pending line separator with an additional nextLine() call before reading the actual text.
Scanner scanner = new Scanner(System.in);
System.out.print("Enter age: ");
int age = scanner.nextInt();
scanner.nextLine();
System.out.print("Enter name: ");
String name = scanner.nextLine();
Integer Range When Reading with Scanner.nextInt()
The value returned by nextInt() must fit in Java’s int type. An int can represent values from -2147483648 through 2147483647. A numeric token outside that range cannot be stored in an int using nextInt().
If the application needs a larger whole-number range, use an appropriate type and input method, such as long with nextLong().
Key Checks for Java Console Integer Input
- Import
java.util.Scannerbefore usingScannerby its simple class name. - Create the scanner with
new Scanner(System.in)when input comes from standard input. - Use
nextInt()when the next console token should be anint. - Use
hasNextInt()when you need to validate a token before reading it. - Remember that non-integer input can cause
InputMismatchException. - Account for the remaining line separator when mixing
nextInt()withnextLine(). - Use a wider numeric type when the required value can exceed the Java
intrange.
Java Integer Console Input Summary
To read an integer from the console in Java, create a Scanner for System.in and call nextInt(). For input that may be invalid, hasNextInt() can verify the next token before it is read. When working with line-oriented input, you can instead read a string with nextLine() and convert it using Integer.parseInt().
In this Java Tutorial, we learned how to read an integer from console.
TutorialKart.com