Reading input
The Scanner line that vanishes, and BufferedReader beating it twelve times on 300,000 integers.
Reading input is where a first Java program meets the outside world, and it has one trap that catches nearly everybody and one performance cliff that matters the moment the input is large.
Scanner, and the line that vanishes
Scanner is the friendly one: it parses tokens for you.
Scanner s = new Scanner(System.in);
System.out.print("age? ");
int age = s.nextInt();
System.out.print("name? ");
String name = s.nextLine();Given the input 30 then Ana:
age? name? ### age = [30]
### name = []
### did it even wait for the second answer?The name is empty, the second prompt printed, and the program never waited. Ana was never read.
The cause is worth understanding rather than memorising a workaround for. nextInt() reads the digits 30 and stops there — it leaves the newline after them sitting in the buffer. nextLine() then reads "everything up to the next newline", finds one immediately, and returns the empty string between them.
So the rule: next, nextInt, nextDouble read tokens and leave the line ending; nextLine reads a line and consumes it. Mixing them is what breaks, and the two fixes are:
int age = s.nextInt();
s.nextLine(); // consume the rest of that line
String name = s.nextLine();
// or: read lines only, and parse yourself
int age = Integer.parseInt(s.nextLine().trim());The second is the one that scales, because it has one rule instead of two.
Two more edges worth knowing:
hasNextInt()beforenextInt(). Otherwise non-numeric input throwsInputMismatchException, and the offending token is not consumed — so a naive retry loop spins forever on the same bad token.- Locale.
nextDoubleuses the default locale, so3.14fails where the locale expects3,14. For anything parsing data rather than talking to a person,new Scanner(in).useLocale(Locale.ROOT).
BufferedReader, and what "faster" actually means
The same 300,000 integers, summed two ways:
### Scanner: 170 ms (sum 44999850000)
### BufferedReader: 14 ms (sum 44999850000)Twelve times. Same answer, and the difference is not a micro-optimisation — it is the difference between a batch job finishing and a competitive-programming submission timing out.
The reason is what each one does per call:
Scanneris a tokeniser built on regular expressions. EverynextInt()matches a pattern against the stream, and it synchronises. That machinery is what makes it pleasant for a prompt and expensive in a loop.BufferedReader.readLine()copies bytes into an array until it sees a line ending. No pattern, no parsing — you callInteger.parseIntyourself, which is a tight loop over digits.
try (BufferedReader r = new BufferedReader(new FileReader("big.txt"))) {
String line;
while ((line = r.readLine()) != null) {
sum += Integer.parseInt(line);
}
}Note the shape of that loop: assign inside the condition, compare to null. It looks odd the first time and it is the idiom, because readLine() returning null is the only way to learn the stream ended.
Under the hood: what each one actually does per call, and what System.in actually is
The 12× number above is not a mystery once you look at what each class does with every character. Scanner's source (java.util.Scanner) keeps its own internal CharBuffer — 1,024 characters by default — and a compiled java.util.regex.Pattern for whitespace as its default delimiter. Every next(), nextInt() or nextLine() call runs a regex match (Matcher.usePattern(...)) against that buffer, advancing a Matcher's internal state machine character by character to find where the next token starts and ends; if the buffer runs out mid-match, it refills from the underlying stream and retries the match from where it left off. That machinery — general enough to recognise any delimiter pattern, not just whitespace, and to parse int, double, BigDecimal and more from the same matched text — is genuinely more work per token than reading bytes, and it is what the Scanner lesson section above meant by "expensive in a loop."
BufferedReader's readLine() does none of that. It keeps a plain char[] buffer too — 8,192 characters by default, eight times Scanner's — and readLine() is a hand-written loop over that array looking for \n or \r, copying characters into a StringBuilder as it goes and refilling the array from the underlying stream when it runs dry. No pattern, no matcher, no general-purpose delimiter logic: it does exactly one job, and Integer.parseInt — a tight loop that reads decimal digits and nothing else — does the rest. That asymmetry, a general regex engine against a special-purpose scan loop, is the entire reason for the twelve-fold gap; it has nothing to do with which class is "modern."
Neither class controls when input actually arrives, though. System.in is a plain InputStream — a static final field the JVM sets up at startup, wired to the process's standard input, whatever that happens to be. InputStream.read() blocks: the call does not return until at least one byte is available or the stream ends, and that is true whether Scanner or BufferedReader is doing the reading — both are wrapping the same blocking stream, so neither is inherently more or less "live." What actually decides when your program sees the first byte you typed is usually the terminal, not Java at all: an interactive terminal normally runs in a line-buffered ("canonical") mode, where the operating system holds every keystroke until Enter is pressed and only then hands the whole line to the process in one delivery. Redirect input from a file or a pipe instead (java App < data.txt, or generator | java App) and that terminal buffering is gone entirely — read() is satisfied by whatever bytes the file or the upstream process has produced, with no notion of "a line" at the OS level at all; readLine() and nextLine() are Java-level concepts built on top of a byte stream that has none.
Try it yourself
Work out where the twelve-fold gap actually goes
Given: Scanner's default internal buffer is 1,024 characters and every token read runs a regex match against it; BufferedReader's default buffer is 8,192 characters and readLine() is a manual scan for a line terminator with no regex at all. For 300,000 integers, one per line, roughly how many buffer refills does each approach need at minimum, and does that gap in refill count look large enough on its own to explain a 12× difference — or does most of the 12× have to come from somewhere else? Where?
Reasoning it through
Assume roughly 7 characters per line (a few digits plus the line ending). 300,000 lines is on the order of 2 million characters. BufferedReader's 8,192-character buffer needs on the order of 2,000,000 / 8,192 ≈ 244 refills; Scanner's 1,024-character buffer needs roughly eight times that, on the order of 1,900 refills. That is a real difference, but it is a difference measured in hundreds to low thousands of extra system-level refill operations across the whole run — nowhere near enough on its own to produce a 12× wall-clock gap over 300,000 iterations. The dominant cost has to be the per-call work, not the per-buffer-refill work: Scanner runs a full regex match through Matcher machinery for every single one of the 300,000 integers, while BufferedReader plus Integer.parseInt runs a tight character-by-character digit scan for each one. Multiplied by 300,000 calls, a general pattern-matching engine costing meaningfully more per call than a specialised digit scanner is exactly the kind of gap that adds up to 12×, while a few thousand extra buffer refills would barely register.
Which to reach for
| Situation | Use |
|---|---|
| a prompt, a handful of values | Scanner — the convenience is worth it |
| a file, or thousands of lines | BufferedReader |
| a whole small file at once | Files.readAllLines(path) |
| a large file, line by line, modern | Files.lines(path) — a stream, and close it |
| production input from a request | neither; the framework has parsed it already |
That last row matters more than it looks. In a Spring service you do not read System.in — the request body arrives parsed and validated, as the API course describes. Scanner and BufferedReader are for programs you run from a terminal: tools, imports, exercises, and the first hundred programs you write.
Closing, and the one you must not close
Both are resources. try-with-resources closes them:
try (BufferedReader r = new BufferedReader(new FileReader(path))) {
...
}The exception is System.in. Closing a Scanner wrapped around it closes the underlying stream, and it cannot be reopened — every later read in that process fails. In a program that reads once at the start, wrapping System.in in a try-with-resources is a bug that only shows up in the second thing that reads.
Misconceptions
- "
BufferedReaderis faster because it has a bigger buffer." The 8× larger buffer (8,192 vs 1,024 characters) helps, but the dominant cost is what happens per token: a regex match throughScanner'sMatcherversus a manual character scan. GiveScanneran 8,192-character buffer and it is still doing regex matching 300,000 times. - "
ScannerandBufferedReaderread input at different speeds from the OS." Both sit on top of the same blockingInputStream(System.in) and get bytes exactly as fast as the OS delivers them. The difference is entirely in how each class turns those bytes into aStringor anintonce it has them.
Sources
java.util.Scannersource (OpenJDK) — the internalCharBuffer,BUFFER_SIZE = 1024, and theMatcher/Pattern-based token search everynext*()call performs.java.io.BufferedReadersource (OpenJDK) —DEFAULT_CHAR_BUFFER_SIZE = 8192and the character-array scanreadLine()performs for a line terminator.java.io.InputStream.read()Javadoc — the blocking contract every stream-reading class, including both of these, is built on.