skip to content

Console & Standard Streams

The standard input, output and error streams, Scanner for parsing input, Console for interactive terminals, and formatted output. Small, but Scanner's pitfalls come up in coding exercises.

part ofJavaoverview, primer and where to startread it →
on this pageshow

explore

questions

14

What is java.util.Scanner and how do you use it to read tokenized input from System.in?

level: juniorimportance: must knowfreq 70%

answer

  1. Source -> tokens -> parsed values
  2. Default delimiter = whitespace
  3. next() = one token, nextLine() = whole line
  4. hasNextInt()/hasNext() check without consuming
  5. Closing a System.in Scanner closes System.in

basics

~20 s

Scanner is a class that reads and parses input. You wrap a source like System.in, then call methods such as nextInt(), nextDouble(), or nextLine() to read the next piece of input as a number or text.

solid answer

~40 s

java.util.Scanner is a simple text scanner that breaks input into tokens using whitespace as the default delimiter and converts each token to a requested type. You construct it over a source (commonly new Scanner(System.in), but also a String, File, or InputStream) and call typed read methods: next() for a token, nextLine() for a whole line, and nextInt()/nextLong()/nextDouble()/nextBoolean() for parsed primitives. Pairing methods like hasNextInt()/hasNext() let you check before reading so you avoid exceptions. It is convenient for console input and small parsing tasks but is not designed for high-throughput reading. When reading System.in interactively you typically do not close the Scanner, because closing it also closes System.in for the rest of the program.

code

java · 7 lines
java
import java.util.Scanner;

Scanner sc = new Scanner(System.in);
while (sc.hasNextInt()) {
    int n = sc.nextInt();   // reads each whitespace-separated integer
    System.out.println(n * n);
}

go deeper

for a junior

Can construct new Scanner(System.in) and read values with nextInt()/next()/nextLine(); knows whitespace is the default separator.

for a middle

Distinguishes token reads from line reads, uses hasNext... guards to avoid exceptions, and knows Scanner can wrap String/File/InputStream sources.

for a senior

Explains Scanner's regex-based parsing and performance trade-offs versus BufferedReader, and the InputMismatchException/NoSuchElementException semantics and buffer behavior.

for a principal

Frames when Scanner is the wrong tool (throughput, untrusted input, localization) and can recommend a robust input strategy and abstraction for a codebase or teaching curriculum.

## What Scanner is `java.util.Scanner` is a class in the Java standard library whose job is to take a stream of characters and **split it into pieces (tokens) and convert those pieces into Java values**. Think of it as a friendly front door for input: you give it a source of text, and it hands you back integers, words, lines, or booleans on demand. ### Key terms (defined) - **Source**: where the characters come from. Common sources are `System.in` (the keyboard/standard input), a `String`, a `File`, or any `InputStream`/`Readable`. - **Token**: one chunk of input separated from the next by a *delimiter*. By default the delimiter is **whitespace** (spaces, tabs, newlines). So in the input `42 hello`, there are two tokens: `42` and `hello`. - **Delimiter**: the pattern (a regular expression) that marks where one token ends and the next begins. Default is whitespace; you can change it with `useDelimiter(...)`. - **Parse**: convert text into a typed value, e.g. the text `"42"` into the `int` `42`. ### Constructing a Scanner ```java Scanner sc = new Scanner(System.in); // read from the keyboard Scanner s2 = new Scanner("1 2 3"); // read from a String ``` The most common one is `new Scanner(System.in)`. ### Reading methods - `next()` — returns the **next whitespace-separated token** as a `String` (e.g. one word). - `nextLine()` — returns **everything up to and including the next line break**, then consumes the line break and gives you the line *without* it. This reads a whole line, even with spaces. - `nextInt()`, `nextLong()`, `nextDouble()`, `nextBoolean()` — read the next token and **parse it** into that primitive type. If the token does not look like that type, they throw `InputMismatchException`. ### Look-before-you-leap methods Each read method has a matching `hasNext...` check that returns a boolean **without consuming input**: ```java while (sc.hasNextInt()) { int n = sc.nextInt(); // safe: we already know an int is next } ``` `hasNext()`/`hasNextLine()` let you loop until input runs out. At end of input these return `false`; calling a `next...` method anyway throws `NoSuchElementException`. ### A complete example ```java import java.util.Scanner; public class Greet { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Age: "); int age = sc.nextInt(); System.out.print("Name: "); String name = sc.next(); System.out.println(name + " is " + age); } } ``` ### What Scanner is good and bad at - **Good**: tiny console programs, quick parsing of structured text, coding-exercise input. Its API is readable and it handles type conversion for you. - **Bad**: large or performance-critical input. Scanner uses regex matching internally and is comparatively slow; for big files prefer `BufferedReader` plus manual parsing. ### Closing `Scanner` implements `AutoCloseable`, so it can be used in try-with-resources. But **be careful with `System.in`**: closing a Scanner wrapped around `System.in` also closes the underlying standard-input stream, and you cannot reopen it. For a normal interactive program you usually just let it be; for a Scanner over a `File` you should close it to release the file handle. With those building blocks — source, token, delimiter, typed read methods, and the `hasNext` checks — you can read essentially any whitespace-structured input.

  • What is the difference between next() and nextLine()?
    next() returns a single whitespace-delimited token (one word), while nextLine() returns the rest of the current line up to the newline and consumes that newline. nextLine() can include spaces; next() stops at the first whitespace.
  • What happens if you call nextInt() but the input is the word 'abc'?
    It throws InputMismatchException because 'abc' cannot be parsed as an int, and the offending token is left in the buffer so a retry without consuming it would fail again.

Scanner is like a deli counter: you hand it a queue of input, and each call to next()/nextInt() serves you the next item, sliced and labeled in the form you asked for.

saying these in an interview costs you the question

  • Thinking Scanner reads byte-by-byte or character-by-character by default rather than token-by-token
  • Believing next() reads a whole line including spaces (that is nextLine())
  • Assuming Scanner is fast enough for large competitive-programming or big-file input
  • Not realizing typed reads can throw InputMismatchException on bad input

context

open as a page

What are the three standard streams in Java, what type is each, and what is each used for?

level: juniorimportance: must knowfreq 70%

basics

~10 s

Java has three standard streams: System.in for reading input, System.out for normal output, and System.err for errors. System.in is an InputStream; System.out and System.err are PrintStreams.

open as a page

How does Console.readPassword() work, and why does it return a char[] instead of a String?

level: middleimportance: must knowfreq 62%

basics

~20 s

readPassword() reads a line of input from the terminal without showing the typed characters (no echo). It returns a char[] instead of a String so you can erase the password from memory afterward by filling the array with zeros - Strings are immutable and can't be wiped.

open as a page

Why does a call to nextLine() right after nextInt() often return an empty string, and how do you fix it?

level: middleimportance: must knowfreq 75%

basics

~20 s

nextInt() reads the number but leaves the leftover newline (Enter key) in the buffer. The next nextLine() then reads that empty leftover instead of the next line. Fix it by adding an extra nextLine() to consume the leftover newline.

open as a page

What is the java.io.Console class, how do you obtain an instance, and why can System.console() return null?

level: juniorimportance: should knowfreq 55%

basics

~20 s

Console is a class for reading and writing text in a terminal. You get it with System.console(). It returns null when the program is not attached to a real interactive terminal (for example, when input or output is redirected, or run inside an IDE).

open as a page

System.in is a raw InputStream. How do you read a line or tokens of text from it correctly, and what must you get right?

level: juniorimportance: should knowfreq 50%

basics

~10 s

System.in gives raw bytes, so wrap it. Use new Scanner(System.in) for tokens/lines, or new BufferedReader(new InputStreamReader(System.in)) and call readLine() for whole lines. Choose a charset and don't close System.in if you still need it.

open as a page

Explain printf/format formatted output in Java: how format specifiers work and what %s, %d, %f, %n, and width/precision flags do.

level: middleimportance: should knowfreq 58%

basics

~20 s

printf/format prints text using a format string with placeholders called format specifiers. Each starts with % - for example %s for a string, %d for an integer, %f for a floating-point number, and %n for a platform-correct newline. You can add width and precision, like %8.2f for a number padded to 8 wide with 2 decimals.

open as a page

Should you close a Scanner that wraps System.in, and what are the consequences either way?

level: middleimportance: should knowfreq 40%

basics

~20 s

Closing a Scanner also closes its underlying source. For a Scanner over System.in that means standard input is closed and can't be read again, so usually you don't close it. For a Scanner over a File, you should close it to free the file.

open as a page

How do you programmatically redirect System.out (or System.err) inside a running JVM, and how do you safely restore it?

level: middleimportance: should knowfreq 55%

basics

~10 s

Call System.setOut(new PrintStream(...)) with your own PrintStream (for example one wrapping a ByteArrayOutputStream or a file). Save the original first and restore it afterward with System.setOut(original).

open as a page

How do Scanner's delimiter and locale settings affect parsing, and what surprises can they cause?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Scanner splits input using a delimiter pattern (whitespace by default) that you can change with useDelimiter(). It also parses numbers using a locale, so in some locales nextDouble() expects a comma as the decimal point and may reject a dot.

open as a page

When should you choose BufferedReader over Scanner for reading input, and why?

level: seniorimportance: should knowfreq 50%

basics

~20 s

Use Scanner when you need easy token parsing of small input. Use BufferedReader when you need speed or to read large input, because it reads lines fast but does not parse types for you, so you split and convert the text yourself.

open as a page

When and why would you use Console (reader()/writer(), printf, readLine) over System.in/System.out directly? Discuss the trade-offs.

level: seniorimportance: nice to knowfreq 35%

basics

~20 s

Use Console when you need an interactive terminal feature that the plain streams can't give you - mainly hidden password input - and a convenient readLine/printf. Use System.in/System.out when you must work with redirected or piped I/O, because Console is null there. In practice, support both: prefer Console when available, fall back to the streams.

open as a page

System.in, System.out and System.err are declared public static final. How can System.setIn/setOut/setErr reassign them, and what does that reveal about the JVM?

level: seniorimportance: nice to knowfreq 30%

basics

~10 s

The three fields are final, so normal Java code cannot reassign them. The setIn/setOut/setErr methods are native: the JVM is allowed to mutate these specific final fields internally, which ordinary bytecode is not.

open as a page

What problems arise from redirecting System.out/err/in to test or capture console I/O, and how would you design around them?

level: principalimportance: nice to knowfreq 28%

basics

~20 s

Redirecting the standard streams changes global, process-wide state, so it is racy under parallel tests, leaks if not restored, and depends on charset/flushing. Better designs inject a PrintStream/Appendable or use a logging framework so you can capture output without touching globals.

open as a page