Console Input & Output (Scanner & BufferedReader)
Read user input cleanly using Scanner and BufferedReader, format console output with printf, and avoid the classic nextLine() buffer pitfall.
- | Built-in
nextInt(),nextDouble(),nextLine()| OnlyreadLine()(parse withInteger.parseInt) | - | 1 KB | 8 KB |
- | Slower (uses regex tokenization) | Much faster (ideal for large inputs) |
- | No | Throws
IOException|
Introduction
Interactive CLI tools and coding-challenge solutions read from standard input (System.in) and write formatted output to System.out. Choosing the right reader impacts both ergonomics and throughput.
Scanner vs BufferedReader
| Feature | java.util.Scanner | java.io.BufferedReader |
|---|---|---|
| Ease of Use | Built-in nextInt(), nextDouble(), nextLine() | Only readLine() (parse with Integer.parseInt) |
| Buffer Size | 1 KB | 8 KB |
| Speed | Slower (uses regex tokenization) | Much faster (ideal for large inputs) |
| Checked Exceptions | No | Throws IOException |
Classic Pitfall: nextInt() Followed by nextLine()
sc.nextInt() reads the digits but leaves the trailing newline \n in the input buffer. Calling sc.nextLine() immediately after consumes that leftover newline and returns an empty string! Always add an extra sc.nextLine(); after numeric reads before reading a full line, or read everything via nextLine() and parse with Integer.parseInt(...).
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)