Java Scanner Class Example in Java
On this page (8sections)
Introduction
The Scanner class in java.util is the most common way to read keyboard input in beginner Java programs. It can read integers, floating-point numbers, words and entire lines from System.in.
When to Use Scanner
Use Scanner when your program needs interactive input from the user — for example, reading a name, age or menu choice in a console application.
Example Program
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.print("Enter your age: ");
int age = sc.nextInt();
System.out.print("Enter your height (cm): ");
double height = sc.nextDouble();
System.out.println("\n--- Profile ---");
System.out.println("Name : " + name);
System.out.println("Age : " + age);
System.out.println("Height : " + height + " cm");
sc.close();
}
}
Sample Output
Enter your name: Thiyagaraaj
Enter your age: 25
Enter your height (cm): 172.5
--- Profile ---
Name : Thiyagaraaj
Age : 25
Height : 172.5 cm
How It Works
new Scanner(System.in)connects the scanner to standard input (keyboard).nextLine()reads a full line of text including spaces.nextInt()andnextDouble()parse numeric tokens from the input stream.- Always call
close()when finished to release the underlying stream.
Best Practices
- Import
java.util.Scannerexplicitly in exam and interview programs. - After
nextInt()ornextDouble(), consume the trailing newline with an extranextLine()if you read text next. - Do not create multiple
Scannerobjects onSystem.inin the same program.
Common Mistakes
- Mixing
next()andnextLine()without understanding token boundaries. - Forgetting to close the scanner in long-running applications.
- Using
Scannerfor file parsing when dedicated readers (BufferedReader,Files.lines) are more efficient.
Frequently Asked Questions
Why does nextInt() skip the next nextLine() call?
nextInt() reads the number but leaves the newline character in the buffer. Call nextLine() once after nextInt() to consume that leftover newline before reading a full line of text.
Should I use Scanner or BufferedReader?
Scanner is easier for mixed input types in learning programs. BufferedReader is often preferred for high-volume text I/O in production because it is faster.