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.in is an InputStream: it delivers raw bytes from the keyboard, a pipe or a redirected file, and knows nothing about lines, numbers or characters. Every way of reading input adds those layers on top:

  • 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 stdin.encoding system property, which reports the encoding of the console's input.
  • 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: Scanner splits the characters into tokens at a delimiter, whitespace by default, and converts tokens with methods such as nextInt, using regular expressions and a locale. BufferedReader only splits into lines and leaves parsing to you.

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() also blocks, because it has to see the next token to answer.

The ways to read input
APISinceGives youBest for
BufferedReader over InputStreamReader(System.in)Java 1.1LinesRobust line input; large input
ScannerJava 5Tokens, typed values, linesSmall interactive programs; parsing mixed text
ConsoleJava 6Lines, passwords without echoInteractive terminal tools
IO.readlnJava 25 (JEP 512)A line, after an optional promptShort 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, so the typed text does not appear on screen; the programs print each value after its prompt instead.

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:

Output
Ana Silva
30
São Paulo
4 8 15
16 23 42 done
Java
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:

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
  1. nextLine() returns the whole line, so the space in "Ana Silva" is kept. next() would have returned only "Ana".
  2. nextInt() reads the token "30" and stops right before the line break.
  3. The next nextLine() therefore returns the empty remainder of the "30" line, shown as []. 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 nextLine() once to finish the line, or read every line with nextLine() and parse it yourself, as the next section does.
  4. hasNextInt() 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", which next() then read.

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:

Output
abc
-5

42
Java
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:

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 Integer.parseInt; -5 parsed but was outside 1 to 100.
  • Bad input never stays behind in a buffer, because each attempt consumed exactly one line. With nextInt, a rejected token stays in the Scanner until something skips it.
  • readLine() returns null 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.
  • 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.

Java
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:

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
  • useDelimiter("[;\\n]") splits on semicolons and line breaks, so each record is read as three typed values.
  • nextDouble 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" throws InputMismatchException. A Scanner created without useLocale uses the machine's default locale, so a program can work on one computer and fail on another. That is why the CSV scanner sets Locale.ROOT.
  • When hasNextInt() is false, the token is still there. Calling nextInt() in a loop without skipping it with next() fails on the same token every time, and a loop that only checks hasNextInt never ends.
  • findInLine searches the current line for a pattern, and match() gives access to its groups.

Scanner traps: read-ahead, close and hidden errors

The next program reads a three-line input file with several Scanner objects on System.in, closes one, and then compares how next and nextLine split the same text.

Java
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:

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 System.in into its buffer. A second Scanner on System.in found nothing, while the first still had "second line" and "third line". Create one Scanner for System.in and pass it around. With a keyboard the loss depends on timing, which makes this bug hard to reproduce.
  • Closing a Scanner closes the stream it wraps. After first.close(), System.in was closed for the rest of the program, and a new Scanner threw NoSuchElementException. Do not close a Scanner over System.in, even though IDEs warn about the unclosed resource.
  • Scanner does not throw IOException. It treats a failed read as the end of input and keeps the exception, which ioException() returned here: "Stream closed". Check it when the difference between "no more input" and "input broke" matters.
  • next() skipped all whitespace, including the empty line, and returned "a", "b" and "c". nextLine() returned the first line with its spaces, then the empty line as an empty string, then "c".

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.

Java
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):

Output
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.
  • Scanner.nextInt was the slowest by a wide margin, around eight times slower than BufferedReader with split. Each token goes through pattern matching, and each number through a locale-aware parser.
  • BufferedReader with split(" ") or with StringTokenizer were both several times faster than Scanner, with split ahead in these runs. A single-character split takes a fast path that avoids the regex engine.
  • 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. The same pattern holds for files; see reading a text file and handling large files.

Console and passwords

System.console() gives access to the terminal the program was started from. Its readPassword reads input without displaying it and returns a char[], so the program can overwrite it after use, which is not possible with an immutable String.

Java
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:

Output
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() returned null. IDE consoles and build tools usually redirect input too, so every program that uses Console needs a fallback, such as a command-line argument, an environment variable or a Scanner. Started directly in a terminal, the same program prompts for both values and does not show the password as it is typed.

For short scripts, Java 25 finalized IO.readln(prompt) and IO.println in java.lang (JEP 512), which print a prompt and read a line in one call; see compact source files.

Which input method to use

Choosing an input method
NeedUse
Simple interactive programs and exercisesScanner(System.in), one instance, never closed
Questions that must be re-asked on bad inputBufferedReader.readLine plus Integer.parseInt and a range check
Parsing words and numbers from a string or small fileScanner with useLocale(Locale.ROOT)
Large or line-based inputBufferedReader over System.in, with split or StringTokenizer
Passwords at a terminalSystem.console().readPassword(), with a fallback when it is null
Quick scripts on Java 25IO.readln(prompt)
Arguments known when the program startsCommand-line arguments or system properties instead of prompts; see properties files