In Java, java.util.Scanner (since Java 5) reads text from a source and breaks it into tokens using a regular-expression delimiter (whitespace by default). You can read words with next(), whole lines with nextLine(), or numbers and booleans directly with nextInt(), nextDouble(), and nextBoolean().
A Scanner works the exact same way whether the text comes from System.in (keyboard), a String literal, or a file/Path. Always check with lookahead methods such as hasNextInt() when input might not match, because a failed read throws InputMismatchException without consuming the bad token. Browse all 36 guides in the Scanner Methods index.
Not thread-safe and not for bulk high-speed input.
Scanner is designed for convenience and small-to-medium parsing, not multiple threads sharing one scanner or reading millions of lines under tight time limits (where BufferedReader is typically faster because it skips regex matching).
Syntax
Java Syntax
Import java.util.Scanner, create a scanner around your source, and read tokens or lines:
Java
import java.util.Locale;
import java.util.Scanner;
Scanner sc = new Scanner("Ada 42 9.5").useLocale(Locale.US);
String word = sc.next(); // "Ada"
int count = sc.nextInt(); // 42
double score = sc.nextDouble(); // 9.5
sc.close();
Reference
Input Sources and Closing Rules
Create a scanner over whichever text source your program needs:
Constructor
Reads from
Closing rule
new Scanner(System.in)
Keyboard / standard input
Create once; closing it also closes System.in for the JVM
new Scanner("a 1 2")
An in-memory String
Safe and ideal with try (Scanner sc = ...)
new Scanner(path, "UTF-8")
A file via Path (Java 7+) or File
Always wrap in try-with-resources so the file handle closes
new Scanner(reader)
Any Readable or InputStream
close() closes the source if it implements Closeable
Pitfall
The Classic nextInt() / nextLine() Newline Pitfall
Token methods like nextInt(), nextDouble(), and next() stop right before the trailing whitespace or newline. If you call nextLine() right after nextInt() on "25 Anna Smith", nextLine() reads the empty remainder of line 1 ("") instead of "Anna Smith"! Fix it in one of two ways: call an extra sc.nextLine() to clear the leftover newline, or read every input as a line with sc.nextLine() and parse numbers with Integer.parseInt(line.trim()).
By default, Scanner splits on p{javaWhitespace}+ (delimiter()), uses radix 10 (radix()), and uses the JVM's default format locale(). Change the separator with useDelimiter() (e.g. "\s*,\s*" for CSV), force dot decimals with useLocale()(Locale.US), switch number bases with useRadix(), or restore all three defaults at once with reset().
Code
Java Examples
Example 1 — Parse a Name, Age, and Score from One Scanner
Scanner works identically whether the source is System.in or a String literal. Here a String supplies deterministic input, and useLocale(Locale.US) ensures 3.75 parses with a dot.
Java
import java.util.Locale;
import java.util.Scanner;
public class ScannerHubBasics {
public static void main(String[] args) {
String input = "Anna 25 3.75\nComputer Science";
try (Scanner sc = new Scanner(input).useLocale(Locale.US)) {
String name = sc.next();
int age = sc.nextInt();
double gpa = sc.nextDouble();
sc.nextLine();
String major = sc.nextLine();
System.out.println("Name: " + name + ", Age: " + age);
System.out.println("GPA: " + gpa + ", Major: " + major);
}
}
}
Try-with-resources and Locale.US. Opening the string scanner inside try (...) guarantees close() runs at the end, and useLocale(Locale.US) makes sure 3.75 parses with a dot on every machine.
Token reads stop before the line break.next() takes "Anna", nextInt() takes 25, and nextDouble() takes 3.75, leaving the newline before "Computer Science".
Clear the newline, then read the line. The extra sc.nextLine() consumes the empty remainder of line 1 so the second nextLine() reads "Computer Science".
Example 2 — Sum Numbers Safely and Skip Non-Numeric Tokens
Checking with hasNextInt() before calling nextInt() prevents crashes, and calling next() discards non-number tokens when they appear.
Java
import java.util.Scanner;
public class ScannerHubValidate {
public static void main(String[] args) {
String data = "15 skip 25 oops 10";
int sum = 0;
int skipped = 0;
try (Scanner sc = new Scanner(data)) {
while (sc.hasNext()) {
if (sc.hasNextInt()) {
sum += sc.nextInt();
} else {
System.out.println("Ignoring: " + sc.next());
skipped++;
}
}
}
System.out.println("Sum = " + sum + ", ignored = " + skipped);
}
}
Output
Ignoring: skip
Ignoring: oops
Sum = 50, ignored = 2
How It Works
Outer loop over every token.sc.hasNext() keeps the loop going until all five whitespace-separated tokens are handled.
Look ahead without consuming.sc.hasNextInt() returns true for 15, 25, and 10, which are consumed by sc.nextInt() and added into sum.
Advance past bad tokens. For "skip" and "oops", hasNextInt() is false, so sc.next() consumes the word and avoids an infinite loop.
Example 3 — Read User Name and Age from the Keyboard (System.in)
For interactive keyboard input, wrap System.in once in main and do not close the scanner if other code still reads from standard input. Here the user types two lines.
Java
import java.util.Scanner;
public class ScannerHubKeyboard {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your age:");
int age = sc.nextInt();
sc.nextLine();
System.out.println("Enter your full name:");
String fullName = sc.nextLine();
System.out.println(fullName + " is " + age + " years old.");
}
}
Sample run
Sample run (the user types the lines shown after the > marker). Run with java ScannerHubKeyboard.
Enter your age:
> 21
Enter your full name:
> Maya Patel
Maya Patel is 21 years old.
How It Works
Keep System.in open when shared. Wrapping System.in in try (...) or calling sc.close() closes standard input for the entire program, so a single long-lived scanner avoids accidental closure.
Discard the Enter key after nextInt(). Typing 21 and pressing Enter leaves a newline in the buffer; sc.nextLine() clears it before prompting for the name.
Read the full name with spaces. The second sc.nextLine() reads "Maya Patel" up to the Enter key, keeping the space between first and last name.
java.util.Scanner (since Java 5) is a text scanner that splits input from System.in, a String, a File/Path, or a Readable into tokens using a regex delimiter (whitespace by default) and parses primitives and strings.
nextInt() reads only the digits and stops right before the newline character left when you pressed Enter. Calling nextLine() immediately reads the rest of that same line, which is empty. Call an extra sc.nextLine() to consume it first.
Be careful: closing a Scanner also closes its underlying stream if it is Closeable. Closing a Scanner on System.in closes System.in for the rest of your program, so future Scanners on System.in will fail to read anything.
Scanner parses numbers using its current Locale. In German or French locales, decimals use a comma (3,5) instead of a dot (3.5). Call sc.useLocale(Locale.US) when your input uses dot decimals.
Use BufferedReader when reading huge files or millions of lines quickly, because Scanner does regex parsing and has higher overhead. Use java.io.Console when you need hidden password input in a terminal.