What is java.util.Scanner and how do you use it to read tokenized input from System.in?
answer
- Source -> tokens -> parsed values
- Default delimiter = whitespace
- next() = one token, nextLine() = whole line
- hasNextInt()/hasNext() check without consuming
- Closing a System.in Scanner closes System.in
basics
~20 sScanner 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 sjava.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 linesimport 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
Can construct new Scanner(System.in) and read values with nextInt()/next()/nextLine(); knows whitespace is the default separator.
Distinguishes token reads from line reads, uses hasNext... guards to avoid exceptions, and knows Scanner can wrap String/File/InputStream sources.
Explains Scanner's regex-based parsing and performance trade-offs versus BufferedReader, and the InputMismatchException/NoSuchElementException semantics and buffer behavior.
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