Quick revision
The short answer
Scanner is slow because it tokenises its input with regular expressions and parses every number through more pattern matching, which costs far more than the reading itself. For 10 million integers we use a BufferedReader with a large buffer and Integer.parseInt on each line, or, for maximum speed, read raw bytes into a big array and build each number from its digits ourselves. Output goes through a buffered writer that is flushed once at the end.
What to remember
In this answer, we saw that Scanner spends its time on regular expressions and locale-aware parsing, which is fine for interactive input but slow for millions of numbers. A BufferedReader with a 64 KB buffer and Integer.parseInt is the everyday fix, and a byte buffer with manual digit parsing is the fastest option when the input is trusted. Output needs the same care: a buffered writer with autoflush off and one flush at the end. Java 25's IO class is for simple programs, not bulk input.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Scanner is slow because it tokenises its input with regular expressions and parses every number through more pattern matching, which costs far more than the reading itself. For 10 million integers we use a BufferedReader with a large buffer and Integer.parseInt on each line, or, for maximum speed, read raw bytes into a big array and build each number from its digits ourselves. Output goes through a buffered writer that is flushed once at the end.
Why this question is asked
Reading numbers from standard input sounds trivial, and for a hundred numbers any approach works. At 10 million lines, the choice of reader decides whether a tool finishes in a fraction of a second or takes several seconds, and the same lesson applies to log processing, data loading and batch jobs. Interviewers ask it to see whether we know what our I/O classes do internally, rather than using Scanner everywhere because it was the first class we learned. In this answer, we will see why Scanner is slow, write the BufferedReader version, write a hand-made byte parser for the fastest version, handle output properly, and look at where Java 25's new console helpers fit.
1Why Scanner Is Slow for Bulk Input
Scanner is a general-purpose tokenizer. Each call to nextInt() asks it to skip delimiters that match a regular expression (whitespace by default), find the next token with another pattern, check that the token looks like an integer in the current locale, which may include grouping separators such as 1,000, and only then convert it. All of that pattern matching runs for every single number.
It also reads its source in fairly small chunks and works on chars, so each byte is decoded from the input charset before any of this starts. None of this matters when a person types one number; with 10 million numbers, it adds up to seconds. As a rough picture on a typical laptop, Scanner takes several seconds for 10 million lines, BufferedReader with parseInt well under a second, and a hand-written byte parser a fraction of that, but measure on your own machine.
| Approach | Work per number | Relative speed |
|---|---|---|
Scanner.nextInt() | regex skip, regex match, locale-aware parse | slowest, often seconds |
BufferedReader + Integer.parseInt | find line end, make a String, parse | several times faster |
| Byte buffer + manual digits | a few arithmetic operations per byte | fastest, no objects per number |
2The Everyday Fix: BufferedReader and Integer.parseInt
For most tools, a BufferedReader with a large buffer is the right answer. It reads 64 KB at a time, finds line ends with a simple scan, and Integer.parseInt is a tight loop over the characters.
We could also write br.lines().mapToLong(Long::parseLong).sum(), which reads nicely and is about as fast. The remaining cost is one String object per line, 10 million short-lived objects, which the garbage collector handles well but which still takes time.
3The Fastest Version: Parse Digits From Raw Bytes
For maximum speed we skip characters and Strings entirely. We read bytes from System.in into a 64 KB array and turn digits into numbers ourselves. Because digits are plain ASCII, no charset decoding is needed.
Notice that there is no object per number at all: each byte is looked at once and costs a comparison and a multiply-add. The trade-off is that we take responsibility for validation. This version does not detect overflow or garbage characters; for a trusted input format in a contest or an internal pipeline that is acceptable, while for user-supplied data the BufferedReader version, which throws NumberFormatException on bad input, is safer. A DataInputStream wrapped around a buffered stream works the same way if we prefer its read methods.
4Writing the Output Efficiently
Output has the same problem in reverse. System.out is a PrintStream that, when attached to a console, may flush often, and printing 10 million lines with System.out.println can take longer than reading the input. We collect output in a buffered writer and flush once.
So the full recipe is symmetrical: big buffer in, cheap parsing, big buffer out, one flush.
5Where Java 25's IO Class Fits
Java 25 finalised compact source files and instance main methods, which come with a small java.lang.IO class offering println, print and readln for simple console programs, so a beginner can write a program without any imports. It is designed for teaching and small scripts, reading one line at a time with no control over buffering, so it is not a replacement for a buffered reader when we need to read millions of lines. The exact methods have changed during the preview releases, so check your version.
6Follow-up questions
Would System.in.read() byte by byte be fast enough?
No. Each call goes through the stream's synchronisation and, because System.in is only lightly buffered, can end up as many small reads. Reading into our own large array and indexing into it is what makes the fast parser fast.
Why pass an explicit charset to InputStreamReader?
Without it, the reader uses the default charset. Since Java 18 the default is UTF-8 on every platform, but tools that must also run on older JVMs or behave the same everywhere should say StandardCharsets.UTF_8 explicitly. For pure digits it rarely matters; for names and text it does.
How would you test which approach is faster?
Generate a file of 10 million random integers once, then run each version with input redirected from that file several times, ignoring the first runs while the JIT warms up. Comparing wall time and allocation with JFR shows both the speed and the garbage created per approach.
7Conclusion
In this answer, we saw that Scanner spends its time on regular expressions and locale-aware parsing, which is fine for interactive input but slow for millions of numbers. A BufferedReader with a 64 KB buffer and Integer.parseInt is the everyday fix, and a byte buffer with manual digit parsing is the fastest option when the input is trusted. Output needs the same care: a buffered writer with autoflush off and one flush at the end. Java 25's IO class is for simple programs, not bulk input.
Open with
Scanner is built for convenience, not volume. Every nextInt call runs regular expressions to skip delimiters and match the token, then does a locale-aware parse, so with 10 million lines the regex work dominates and it takes seconds.
Then, if they want more
My default replacement is a BufferedReader around an InputStreamReader on System.in with UTF-8 and a 64 KB buffer, reading each line and calling Integer.parseInt. That is several times faster and still validates input, because parseInt throws on garbage.
If I need the absolute maximum, I read raw bytes from System.in into a 64 KB array and build each number from its digits: skip separators, check for a minus sign, then n times ten plus the digit.
That creates no String per number and touches each byte once, though I give up overflow and format checking, so I only use it for trusted input.
I also handle output the same way: a PrintWriter over a BufferedWriter with autoflush off and a single flush at the end, because printing millions of lines through System.out directly can be slower than the reading. Java 25 has the new java.lang.IO class with println and readln, but that is for simple console programs, not bulk input.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 25, Java 18
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A command-line tool must read up to 10 million integers from standard input as fast as...": https://scrivio-interview-library.netlify.app/java/io-and-nio/d8145a4be3/