Reading input in Java: Scanner and Console
Scanner turns text input, from the keyboard, a file or a string, into tokens, numbers and lines. It is convenient but has rules that surprise almost everyone once: the empty line after nextInt, the locale-dependent number format, and the System.in that close() shuts for good. This page runs each case, shows a robust line-based alternative, measures Scanner against BufferedReader, and covers Console for passwords.
Contents
How console input works in Java
System.inInputStream
- Decoding: a reader turns the bytes into characters with a charset. Since Java 18 the default is UTF-8 (JEP 400). Java 25 adds the
system property, which reports the encoding of the console's input.stdin.encoding - Buffering: the reader takes a block of input at once and serves your calls from memory. That is fast, but it means the reader owns data you have not asked for yet.
- Splitting and parsing:
splits the characters into tokens at a delimiter, whitespace by default, and converts tokens with methods such asScanner , using regular expressions and a locale.nextInt only splits into lines and leaves parsing to you.BufferedReader
A key detail: when input comes from a keyboard, the terminal delivers nothing until the user presses Enter, and a read call blocks until then. hasNextInt()
| API | Since | Gives you | Best for |
|---|---|---|---|
BufferedReaderInputStreamReader(System.in) | Java 1.1 | Lines | Robust line input; large input |
Scanner | Java 5 | Tokens, typed values, lines | Small interactive programs; parsing mixed text |
Console | Java 6 | Lines, passwords without echo | Interactive terminal tools |
IO.readln | Java 25 (JEP 512) | A line, after an optional prompt | Short scripts and teaching |
All programs below were compiled and run on JDK 21. Those that read standard input were run with a prepared input file redirected to them, as in java ReadStdin < input.txt
Reading from standard input with Scanner
The program asks for a name, an age and a city, then reads numbers until it meets a word. The name contains a space and the city a non-ASCII letter, so both the line-versus-token difference and the decoding are visible. The input file is:
Ana Silva
30
São Paulo
4 8 15
16 23 42 done
import java.util.Scanner;
public class ReadStdin {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Name: ");
String name = in.nextLine(); // the whole line, spaces included
System.out.println(name);
System.out.print("Age: ");
int age = in.nextInt(); // reads "30", leaves the newline behind
System.out.println(age);
// The classic trap: this nextLine returns the empty rest of the "30" line
String leftover = in.nextLine();
System.out.println("nextLine right after nextInt returned [" + leftover + "]");
System.out.print("City: ");
String city = in.nextLine();
System.out.println(city);
// Read numbers until something that is not a number appears
int sum = 0;
int count = 0;
while (in.hasNextInt()) {
sum += in.nextInt();
count++;
}
String stop = in.next();
System.out.println("read " + count + " numbers, sum " + sum + ", stopped at \"" + stop
+ "\"");
System.out.println(name + " (" + age + ") from " + city);
}
}
Output:
Name: Ana Silva
Age: 30
nextLine right after nextInt returned []
City: São Paulo
read 6 numbers, sum 108, stopped at "done"
Ana Silva (30) from São Paulo
returns the whole line, so the space in "Ana Silva" is kept.nextLine() would have returned only "Ana".next() reads the token "30" and stops right before the line break.nextInt()- The next
therefore returns the empty remainder of the "30" line, shown asnextLine() . Without the extra call, the program would have stored an empty city and then failed to parse "São Paulo" as a number. The fix is what the program does: call[] once to finish the line, or read every line withnextLine() and parse it yourself, as the next section does.nextLine() checks the next token without consuming it. The loop read 6 numbers across two lines (4 + 8 + 15 + 16 + 23 + 42 = 108) and stopped at "done", whichhasNextInt() then read.next()
Robust input: read lines, then parse and validate
Mixing token and line methods is what causes the trap above. Reading every answer as a whole line and parsing it yourself avoids it, and also makes it easy to re-ask after bad input. The input contains a word, a number out of range, an empty line and finally a valid number:
abc
-5
42
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
public class ValidatedInput {
// Reads whole lines and parses them, so bad input never leaves the reader confused
static int askInt(BufferedReader in, String prompt, int min, int max) throws IOException {
while (true) {
System.out.print(prompt);
String line = in.readLine();
if (line == null) {
throw new IOException("input ended before a valid number was entered");
}
System.out.println(line.isEmpty() ? "(empty line)" : line); // echo redirected input
try {
int value = Integer.parseInt(line.strip());
if (value >= min && value <= max) {
return value;
}
System.out.println(" must be between " + min + " and " + max);
} catch (NumberFormatException e) {
System.out.println(" not a whole number, try again");
}
}
}
public static void main(String[] args) throws IOException {
// System.in carries bytes; say which charset they are in
Charset cs = Charset.defaultCharset();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in, cs));
int quantity = askInt(in, "Quantity (1-100): ", 1, 100);
System.out.println("accepted: " + quantity);
System.out.println("decoding System.in as " + cs);
}
}
Output:
Quantity (1-100): abc
not a whole number, try again
Quantity (1-100): -5
must be between 1 and 100
Quantity (1-100): (empty line)
not a whole number, try again
Quantity (1-100): 42
accepted: 42
decoding System.in as UTF-8
- Each wrong answer got its own message, and the program asked again. "abc" and the empty line failed
; -5 parsed but was outside 1 to 100.Integer.parseInt - Bad input never stays behind in a buffer, because each attempt consumed exactly one line. With
, a rejected token stays in thenextInt until something skips it.Scanner returnsreadLine() when input ends, for example when a pipe closes or the user presses Ctrl+D (Ctrl+Z on Windows). The method turns that into an exception instead of looping forever.null- The reader was given a charset explicitly. Here it was UTF-8, the default since Java 18.
Parsing text with Scanner
Scanner works on any text source, not just the keyboard. The program parses semicolon-separated records, reads numbers in two locales, recovers from a token that is not a number, and extracts a value with a regular expression.
import java.util.InputMismatchException;
import java.util.Locale;
import java.util.Scanner;
public class ScannerParsing {
public static void main(String[] args) {
// Scanner reads from any source: a String, a File, a Path, an InputStream
Scanner csv = new Scanner("Ana;30;1.75\nBen;25;1.82").useDelimiter("[;\\n]")
.useLocale(Locale.ROOT); // "." as decimal point on every machine
while (csv.hasNext()) {
System.out.printf("name=%s age=%d height=%.2f%n", csv.next(), csv.nextInt(),
csv.nextDouble());
}
// Number formats follow the Scanner's locale
Scanner german = new Scanner("3,5 1.234,5").useLocale(Locale.GERMANY);
System.out.println("German locale: " + german.nextDouble() + " and " + german.nextDouble());
Scanner us = new Scanner("3,5").useLocale(Locale.US);
try {
us.nextDouble();
} catch (InputMismatchException e) {
System.out.println("US locale reading \"3,5\": InputMismatchException");
}
// A failed nextInt does not consume the token: skip it or you loop forever
Scanner mixed = new Scanner("10 ten 20");
int total = 0;
while (mixed.hasNext()) {
if (mixed.hasNextInt()) {
total += mixed.nextInt();
} else {
System.out.println("skipping \"" + mixed.next() + "\"");
}
}
System.out.println("total of the numbers: " + total);
// findInLine searches the current line with a regular expression
Scanner log = new Scanner("2026-01-15 ERROR code=503 retry=3");
System.out.println("code found: " + log.findInLine("code=(\\d+)") + ", group 1: "
+ log.match().group(1));
}
}
Output:
name=Ana age=30 height=1.75
name=Ben age=25 height=1.82
German locale: 3.5 and 1234.5
US locale reading "3,5": InputMismatchException
skipping "ten"
total of the numbers: 30
code found: code=503, group 1: 503
splits on semicolons and line breaks, so each record is read as three typed values.useDelimiter("[;\\n]") uses the Scanner's locale. In German, "3,5" is 3.5 and "1.234,5" is 1234.5; with the US locale, "3,5" throwsnextDouble . A Scanner created withoutInputMismatchException uses the machine's default locale, so a program can work on one computer and fail on another. That is why the CSV scanner setsuseLocale .Locale.ROOT- When
is false, the token is still there. CallinghasNextInt() in a loop without skipping it withnextInt() fails on the same token every time, and a loop that only checksnext() never ends.hasNextInt searches the current line for a pattern, andfindInLine gives access to its groups.match()
Scanner traps: read-ahead, close and hidden errors
The next program reads a three-line input file with several ScannerSystem.innextnextLine
import java.util.NoSuchElementException;
import java.util.Scanner;
public class ScannerTraps {
public static void main(String[] args) {
// Trap 1: a Scanner reads ahead, so a second Scanner on System.in misses data
Scanner first = new Scanner(System.in);
System.out.println("first scanner: " + first.nextLine());
Scanner second = new Scanner(System.in);
System.out.println("second scanner has a line: " + second.hasNextLine());
System.out.println("first scanner still has: " + first.nextLine() + ", "
+ first.nextLine());
// Trap 2: closing a Scanner closes System.in for the rest of the program
first.close();
Scanner third = new Scanner(System.in);
try {
third.nextLine();
} catch (NoSuchElementException e) {
System.out.println("after close(), a new Scanner: NoSuchElementException");
}
// Trap 3: Scanner hides I/O errors instead of throwing them
System.out.println("ioException() after the failed read: "
+ (third.ioException() == null ? "null" : third.ioException().getMessage()));
// Trap 4: next() and nextLine() count differently
Scanner s = new Scanner(" a b\n\nc");
System.out.println("next(), next(), next(): " + s.next() + s.next() + s.next());
Scanner t = new Scanner(" a b\n\nc");
System.out.println("nextLine() x3: [" + t.nextLine() + "] [" + t.nextLine() + "] ["
+ t.nextLine() + "]");
}
}
Output:
first scanner: first line
second scanner has a line: false
first scanner still has: second line, third line
after close(), a new Scanner: NoSuchElementException
ioException() after the failed read: Stream closed
next(), next(), next(): abc
nextLine() x3: [ a b] [] [c]
- The first Scanner read one line, but it had already taken all three lines from
into its buffer. A second Scanner onSystem.in found nothing, while the first still had "second line" and "third line". Create one Scanner forSystem.in and pass it around. With a keyboard the loss depends on timing, which makes this bug hard to reproduce.System.in - Closing a Scanner closes the stream it wraps. After
,first.close() was closed for the rest of the program, and a new Scanner threwSystem.in . Do not close a Scanner overNoSuchElementException , even though IDEs warn about the unclosed resource.System.in - Scanner does not throw
. It treats a failed read as the end of input and keeps the exception, whichIOException returned here: "Stream closed". Check it when the difference between "no more input" and "input broke" matters.ioException() skipped all whitespace, including the empty line, and returned "a", "b" and "c".next() returned the first line with its spaces, then the empty line as an empty string, then "c".nextLine()
How fast is Scanner?
Scanner's regular expressions cost time, which matters for bulk input such as data files piped into a program or programming contest input. The program sums 500,000 numbers, 10 per line, four ways, from an in-memory copy of the input so the disk plays no part. Each way runs 3 times and the fastest run is shown.
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Random;
import java.util.Scanner;
import java.util.StringTokenizer;
public class InputSpeed {
static final int COUNT = 500000;
interface Reader {
long sum(InputStream in) throws IOException;
}
static long scanner(InputStream in) {
Scanner s = new Scanner(in);
long sum = 0;
for (int i = 0; i < COUNT; i++) {
sum += s.nextInt();
}
return sum;
}
static long readerSplit(InputStream in) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
long sum = 0;
String line;
while ((line = r.readLine()) != null) {
for (String part : line.split(" ")) {
sum += Integer.parseInt(part);
}
}
return sum;
}
static long readerTokenizer(InputStream in) throws IOException {
BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
long sum = 0;
String line;
while ((line = r.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
sum += Integer.parseInt(st.nextToken());
}
}
return sum;
}
// Parses digits straight from a byte array, no Strings at all
static long rawBytes(InputStream in) throws IOException {
byte[] buf = new byte[1 << 16];
long sum = 0;
int n = 0;
boolean inNumber = false;
int len;
while ((len = in.read(buf)) != -1) {
for (int i = 0; i < len; i++) {
int b = buf[i];
if (b >= '0' && b <= '9') {
n = n * 10 + (b - '0');
inNumber = true;
} else if (inNumber) {
sum += n;
n = 0;
inNumber = false;
}
}
}
return inNumber ? sum + n : sum;
}
static void measure(String label, byte[] input, Reader r) throws IOException {
long best = Long.MAX_VALUE;
long sum = 0;
for (int i = 0; i < 3; i++) {
long start = System.nanoTime();
sum = r.sum(new ByteArrayInputStream(input));
best = Math.min(best, System.nanoTime() - start);
}
System.out.printf("%-34s %5d ms sum %,d%n", label, best / 1000000, sum);
}
public static void main(String[] args) throws IOException {
// 500,000 numbers, 10 per line: the shape of typical bulk input on stdin
StringBuilder sb = new StringBuilder();
Random rnd = new Random(7);
for (int i = 1; i <= COUNT; i++) {
sb.append(rnd.nextInt(1000000)).append(i % 10 == 0 ? '\n' : ' ');
}
byte[] input = sb.toString().getBytes(StandardCharsets.UTF_8);
System.out.printf("%,d numbers, %,d bytes, best of 3%n", COUNT, input.length);
readerSplit(new ByteArrayInputStream(input)); // warm-up
measure("Scanner.nextInt", input, InputSpeed::scanner);
measure("BufferedReader + split", input, InputSpeed::readerSplit);
measure("BufferedReader + StringTokenizer", input, InputSpeed::readerTokenizer);
measure("raw bytes, hand-parsed", input, InputSpeed::rawBytes);
}
}
Output (rough comparison on a 2-CPU Linux VM, JDK 21; absolute times will differ on yours):
500,000 numbers, 3,444,325 bytes, best of 3
Scanner.nextInt 131 ms sum 249,932,977,144
BufferedReader + split 16 ms sum 249,932,977,144
BufferedReader + StringTokenizer 38 ms sum 249,932,977,144
raw bytes, hand-parsed 2 ms sum 249,932,977,144
- All four computed the same sum.
was the slowest by a wide margin, around eight times slower thanScanner.nextInt withBufferedReader . Each token goes through pattern matching, and each number through a locale-aware parser.split withBufferedReader or withsplit(" ") were both several times faster than Scanner, withStringTokenizer ahead in these runs. A single-charactersplit takes a fast path that avoids the regex engine.split- Parsing digits straight from a byte array was fastest, because it creates no strings at all. It only works for simple ASCII input.
For typical interactive programs, which read a few lines, Scanner's speed does not matter. For input measured in megabytes, use BufferedReader
Console and passwords
System.console()readPasswordchar[]String
import java.io.Console;
public class ConsoleCheck {
public static void main(String[] args) {
// System.console() is null when input or output is redirected (pipes, IDEs, CI)
Console console = System.console();
if (console == null) {
System.out.println("no console: input is not an interactive terminal");
System.out.println("falling back to Scanner or command-line arguments");
return;
}
String user = console.readLine("User: ");
char[] password = console.readPassword("Password: "); // typed without echo
try {
console.printf("Hello %s, your password has %d characters%n", user, password.length);
} finally {
java.util.Arrays.fill(password, ' '); // wipe it from memory
}
}
}
Output when run with redirected input, as for this page:
no console: input is not an interactive terminal
falling back to Scanner or command-line arguments
On JDK 21, and also when this program was run with JDK 25 with redirected input, System.console()nullConsoleScanner
For short scripts, Java 25 finalized IO.readln(prompt)IO.printlnjava.lang
Which input method to use
| Need | Use |
|---|---|
| Simple interactive programs and exercises | Scanner(System.in) |
| Questions that must be re-asked on bad input | BufferedReader.readLineInteger.parseInt |
| Parsing words and numbers from a string or small file | ScanneruseLocale(Locale.ROOT) |
| Large or line-based input | BufferedReaderSystem.insplitStringTokenizer |
| Passwords at a terminal | System.console().readPassword()null |
| Quick scripts on Java 25 | IO.readln(prompt) |
| Arguments known when the program starts | Command-line arguments or system properties instead of prompts; see |