What is the Scanner Class?
Scanner is a class in the java.util package used to read input — from the keyboard (System.in), a file, or even a String. It breaks input into tokens (words, numbers, lines) using whitespace as the default delimiter, and provides methods to parse each token into the type you need (int, double, String, etc.).
Think of it as a "reader + parser" combined — it doesn't just grab raw text, it converts it into the exact data type your program expects.
Importing and Creating a Scanner
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
System.in tells it to read from the keyboard/console. You can also pass a File object or a String to read from those sources instead.
Basic Example
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.println("Hello " + name + ", you are " + age + " years old.");
sc.close();
}
}
Commonly Used Methods
Method Reads
nextInt() an int
nextLong() a long
nextDouble() a double
nextFloat() a float
next() a single word (stops at whitespace)
nextLine() an entire line, including spaces
nextBoolean() true/false
hasNext() checks if more input is available
hasNextInt() checks if the next token is a valid int
The Classic Bug: Mixing nextInt() and nextLine()
Scanner sc = new Scanner(System.in);
System.out.print("Enter age: ");
int age = sc.nextInt(); // reads the number, but leaves "\n" in the buffer
System.out.print("Enter name: ");
String name = sc.nextLine(); // reads that leftover "\n" instead of waiting for real input!
nextInt() only consumes the digits — it leaves the newline character behind in the input buffer. The next nextLine() call then grabs that leftover newline instead of pausing for actual input, so name ends up empty.
Fix:
** consume the leftover newline with an extra nextLine() call:**
int age = sc.nextInt();
sc.nextLine();
String name = sc.nextLine();
nextInt() only consumes the digits — it leaves the newline character behind in the input buffer. The next nextLine() call then grabs that leftover newline instead of pausing for actual input, so name ends up empty.
Fix:
consume the leftover newline with an extra nextLine() call:
int age = sc.nextInt();
sc.nextLine(); // clears the leftover newline
String name = sc.nextLine();
Reading Multiple Inputs in a Loop
Scanner sc = new Scanner(System.in);
System.out.print("How many numbers? ");
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
Always Close Your Scanner
sc.close();
Summary
Scanner reads and parses input from the console, a file, or a string.
Use next()/nextLine() for text, and nextInt()/nextDouble()/etc. for numbers.
Watch out for the nextInt() → nextLine() buffer bug — it's the #1 gotcha for beginners.
Always close your Scanner when done.