Read Integer From User in Java
beginner· Basics & I/O · I/O
Problem
Scanner.nextInt() reads the next whitespace-separated token from the console and parses it directly into an int, failing with an exception if the typed text isn't a valid integer.
Read a single integer from the console and print it.
Input
42
Output
You entered: 42
Java Program
Java
import java.util.Scanner;
public class ReadIntegerFromUser {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an integer: ");
int value = sc.nextInt(); // reads and parses the typed integer
System.out.println(value); // echo back — this compiler doesn't echo typed input itself
System.out.println("You entered: " + value);
}
}Output
Enter an integer: 42
You entered: 42
Core Logic
Scanner reads the typed integer directly, with no manual parsing needed.
How It Works
- 1
new Scanner(System.in)creates a reader attached to the console. - 2
System.out.print(...)shows a prompt without a trailing newline. - 3
sc.nextInt()reads the next token and parses it straight into anint. - 4
System.out.println(value)echoes the value right after the prompt, since most online compilers don't echo typed input themselves the way a real terminal does. - 5A separate labeled line then confirms what was read.
Typing
42 makes sc.nextInt() return 42, which is then printed as You entered: 42.💡
Key Point: nextInt() throws InputMismatchException if the next token isn't a valid integer — it doesn't silently return 0 or skip bad input.
Key Concepts
ScannernextInt()console input
Approach 2: BufferedReader
Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class ReadIntegerBufferedReader {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter an integer: ");
// readLine() returns a String, so parse it into an int explicitly
int value = Integer.parseInt(br.readLine());
System.out.println(value); // echo back — this compiler doesn't echo typed input itself
System.out.println("You entered: " + value);
}
}
Output
Enter an integer: 42
You entered: 42
Core Logic
BufferedReader reads the line as raw text first, then Integer.parseInt() converts it into an int explicitly.
How It Works
- 1
new BufferedReader(new InputStreamReader(System.in))wraps standard input in a buffered character reader. - 2
br.readLine()reads the whole line as aString. - 3
Integer.parseInt(...)converts that string into anint, sincereadLine()does no numeric parsing on its own. - 4The method signature adds
throws IOException, sincereadLine()can throw a checked exception.
Typing
42 gives the string "42", which Integer.parseInt() converts into the int 42.💡
Key Point: BufferedReader is the faster choice for reading large volumes of input, at the cost of this extra manual parsing step Scanner handles for you.
Key Concepts
BufferedReaderreadLine()Integer.parseInt()