Sub topic 13
Choosing the right approach
This chapter compares the four ways to read console input covered in this tutorial: Scanner, java.io.Console, java.io.IO (Java 25) and BufferedReader. It assumes you have read the earlier chapters on each of them. You should be comfortable with hasNextInt, the leftover newline, end of input and closing System.in.
No option is best everywhere. The right choice depends on four things:
- the shape of the input (tokens or lines)
- whether a person or a pipe supplies it
- whether the input is secret
- which Java version you can rely on
What each option does best
Each approach wraps standard input differently, so each has different strengths.
| Approach | Reads | Strength | Main cost |
|---|---|---|---|
| `Scanner` | Tokens and lines, with parsing | Built-in `nextInt`, `nextDouble`, `hasNextInt`, delimiters | Slower on large input. Mixing token and line reads leaves a newline behind |
| `Console` | Lines and passwords | `readPassword` does not echo. Prompt and read in one call | `System.console()` can return `null`. Lines only, no parsing |
| `IO` (Java 25) | Lines | Shortest code. Prompt and read in one call. No `Scanner` object to manage | Requires Java 25. You parse numbers yourself |
| `BufferedReader` | Lines | Fast, simple, no hidden parsing | You handle `IOException` and parse everything yourself |
Decision criteria
Is the input secret?
Use Console.readPassword. It is the only option in this chapter that turns off echo, so the characters do not appear on screen. It returns a char[] that you can overwrite after use. A String stays in memory until garbage collection and cannot be cleared.
Check for null before using it. In older Java versions, System.console() returns null when input or output is redirected or the program runs without a terminal, such as inside some IDEs. Newer versions return a console object more often. Your program should still handle the case where none exists, and Console.isTerminal() (Java 22 and later) tells you whether you are talking to a real terminal.
Do you need parsed numbers?
If the input is a stream of numbers or words, Scanner is the most direct choice. Its hasNextInt and nextInt pair gives you validation without exception handling, and useDelimiter handles comma-separated or otherwise unusual formats.
If the input is line-oriented, the other three options work well. Convert with Integer.parseInt and catch NumberFormatException. This is the better fit when each line has its own meaning, such as a command followed by arguments.
Is the input large?
Scanner uses regular expressions to find tokens, which costs time. For a few lines typed by a person, you will never notice. For hundreds of thousands of numbers piped in from a file, BufferedReader is much faster. Programming-contest code uses it for this reason.
Which Java version can you assume?
IO.readln exists only in Java 25 and later. Use it in new code, scripts and teaching examples where that version is guaranteed. Code that must run on Java 17 or 21 should use Scanner or BufferedReader.
Does the program need to detect end of input?
All four approaches can detect it, but each signals it differently:
ScanneranswershasNext()orhasNextLine()withfalse. If you callnextornextLineanyway, it throwsNoSuchElementException.BufferedReader.readLine()returnsnull.Console.readLine()returnsnull.IO.readln()builds on console reading, so treatnullas the end-of-input signal here too.
Pick the style that fits the surrounding code. A while (in.hasNextInt()) loop reads naturally for numbers. A while ((line = reader.readLine()) != null) loop reads naturally for lines.
The same task four ways
Suppose a program must ask for a name and an age. Here are the four versions.
With Scanner, use nextLine for the name and take the age from a line, so no newline is left over:
import java.util.Scanner;
public class GreeterScanner {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Name: ");
String name = in.nextLine();
System.out.print("Age: ");
int age = Integer.parseInt(in.nextLine().trim());
System.out.println(name + " is " + age);
}
}Reading both values with nextLine avoids the leftover newline entirely. The cost is that you now parse the number yourself, which is the same work the other three versions do.
With BufferedReader:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class GreeterReader {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Name: ");
String name = reader.readLine();
System.out.print("Age: ");
int age = Integer.parseInt(reader.readLine().trim());
System.out.println(name + " is " + age);
}
}With Console, including the null check:
import java.io.Console;
public class GreeterConsole {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.err.println("No console available");
return;
}
String name = console.readLine("Name: ");
int age = Integer.parseInt(console.readLine("Age: ").trim());
console.printf("%s is %d%n", name, age);
}
}With IO in a Java 25 compact source file, run as java Greeter.java:
void main() {
String name = IO.readln("Name: ");
int age = Integer.parseInt(IO.readln("Age: ").trim());
IO.println(name + " is " + age);
}The IO version is the shortest and has nothing to close. The BufferedReader version is the only one that forces you to declare IOException.
Failure modes to plan for
Bad numbers
Integer.parseInt throws NumberFormatException for text like abc or an empty string. Scanner.nextInt throws InputMismatchException for the same input, and it does not consume the bad token. A retry loop that calls nextInt again without discarding the token will spin forever. Use the hasNextInt pattern from the validation chapter, or wrap a line parse in try/catch and ask again.
Several readers on one stream
Do not create two Scanner objects, or a Scanner and a BufferedReader, on System.in in the same program. Each one buffers input ahead of what you have consumed. Text that one reader has buffered is invisible to the other, so input appears to vanish. Create one reader and pass it to the methods that need it.
The same warning applies when you mix IO.readln with a Scanner. IO reads through the console, and your Scanner reads System.in through its own buffer. Pick one source per program.
Closing the stream too early
Closing a Scanner on System.in closes System.in, and you cannot reopen it. Put the close at the end of the program with try-with-resources, as in the SumAll example. Do not close it inside a helper method that other code will call again. Console and IO have no close to worry about.
Input piped from a file
When a program runs as java App < data.txt, nobody is typing. Prompts are still printed, which clutters output. A Console may be missing, or it may not behave interactively. If your program must work both interactively and in a pipeline, Scanner and BufferedReader behave the same in both cases. That predictability is a good reason to choose them for tools and scripts.
A practical rule set
- Reading a password:
Console.readPassword, with anullcheck. - Teaching, quick scripts and Java 25 code that reads lines:
IO.readln. - Reading numbers or words with validation:
ScannerandhasNextInt. - Reading large line-based input, or running in pipelines:
BufferedReader. - Whatever you choose, read from
System.inthrough one object only.
Exercises
Exercise
A command-line tool must read two million integers piped in from a file, one per line, and sum them. Which approach fits best, and why?
Show answer
BufferedReader. It reads lines quickly without regular-expression token matching, and Integer.parseInt converts each line. Scanner would work but is noticeably slower at this volume.
Exercise
Your program runs on Java 21 and asks the user for a password. Which class do you use, and what must you check before calling it?
Show answer
Use java.io.Console with readPassword, which does not echo the typed characters. First check that System.console() did not return null, because no console may be attached when input or output is redirected.
Exercise
A program creates a Scanner on System.in in main, then calls a helper that creates a BufferedReader on System.in and reads one line. Some typed input never reaches the helper. What is wrong, and what is the fix?
Show answer
Each reader buffers input ahead of what it has consumed, so the Scanner has already taken text that the BufferedReader never sees. Create a single reader and pass it to the helper, or use only one of the two classes.