Sub topic 8
Closing the Scanner
This chapter assumes you can create a Scanner on System.in and read tokens and lines from it. It also assumes you know try-with-resources and the exceptions NoSuchElementException and IllegalStateException. Here you will learn what Scanner.close() does to System.in, why that matters, and how to structure a program so you close once and only once.
What close() does
A Scanner implements Closeable, so it has a close() method. The method does two things:
- It marks the scanner as closed. Every later call to a reading method such as
next(),nextInt(),nextLine(),hasNext()orhasNextInt()throwsIllegalStateExceptionwith the messageScanner closed. - If the source the scanner reads from also implements
Closeable, the scanner closes it too.
System.in is an InputStream, and InputStream implements Closeable. So new Scanner(System.in).close() closes System.in itself, not only the scanner.
Calling close() a second time on the same scanner does nothing. It is safe to close twice, but you gain nothing by it.
import java.util.Scanner;
public class ClosedScanner {
public static void main(String[] args) {
Scanner in = new Scanner("10 20 30");
System.out.println(in.nextInt());
in.close();
in.close(); // harmless, second call is ignored
try {
in.nextInt();
} catch (IllegalStateException e) {
System.out.println("Caught: " + e.getMessage());
}
}
}This prints 10, then Caught: Scanner closed. The source here is a String, which is not Closeable, so closing only affects the scanner. With System.in the effect reaches further.
Why closing System.in is a problem
System.in is a single stream shared by the whole JVM. Once you close it, you cannot reopen it. Any later code that reads standard input sees a dead stream.
When a scanner reads from a closed stream, the underlying read throws an IOException. The scanner catches that exception and treats the input as ended. The result is that reading methods on a new scanner behave as if the user had pressed end-of-input immediately:
hasNext(),hasNextInt()andhasNextLine()returnfalse.next(),nextInt()andnextLine()throwNoSuchElementException.
The following program shows the most common version of this bug. Each helper method creates its own scanner and closes it with try-with-resources.
import java.util.Scanner;
public class ClosedTwice {
static int readCount() {
try (Scanner in = new Scanner(System.in)) {
System.out.print("Count: ");
return in.nextInt();
}
}
static String readTitle() {
try (Scanner in = new Scanner(System.in)) {
System.out.print("Title: ");
return in.nextLine();
}
}
public static void main(String[] args) {
int count = readCount();
String title = readTitle();
System.out.println(count + " x " + title);
}
}Each method looks correct on its own. Run the program and type 3 and Enter at the first prompt. The first helper closes System.in on its way out. The second helper then builds a scanner on a closed stream, and nextLine() throws NoSuchElementException: No line found. The title prompt never gets a chance to accept anything.
A second, quieter bug: two live scanners
You do not need to close anything to lose input. A Scanner reads ahead. It fills an internal buffer from the stream, 1024 characters at a time, and serves your calls from that buffer. If you create two scanners on System.in, the first one may swallow input that you meant for the second.
With a user typing at a terminal, this usually goes unnoticed because the terminal hands over one line at a time. It shows up quickly when input is piped from a file or another command, because the first scanner pulls in the whole input at once. The second scanner then sees nothing.
The rule that avoids both bugs is the same: create one scanner on System.in and share it.
The fix: one scanner, passed as a parameter
Create the scanner once, near the top of the program, and pass it to every method that reads input. Close it once, where it was created.
import java.util.Scanner;
public class SharedScanner {
static int readCount(Scanner in) {
System.out.print("Count: ");
int count = in.nextInt();
in.nextLine(); // discard the rest of the line
return count;
}
static String readTitle(Scanner in) {
System.out.print("Title: ");
return in.nextLine();
}
public static void main(String[] args) {
try (Scanner in = new Scanner(System.in)) {
int count = readCount(in);
String title = readTitle(in);
System.out.println(count + " x " + title);
}
}
}The helpers do not own the scanner, so they never close it. The code that creates a resource is the code that closes it. This is the same ownership rule you apply to files and database connections.
The extra in.nextLine() in readCount is the leftover-newline fix from the earlier chapter. It stays in place.
Should you close a Scanner on System.in at all?
Many Java programs never close their System.in scanner, and that is acceptable in practice. Compare the two choices:
| Choice | What you get | What it costs |
|---|---|---|
| Close at the end of `main` with try-with-resources | No IDE or compiler warning about a resource leak. Clear ownership. | `System.in` is closed. Any code that runs afterward cannot read input. |
| Never close | `System.in` stays usable. The process exit releases everything. | Linters and IDEs flag a resource leak. A reader may wonder whether it was forgotten. |
For a short command-line program, closing at the end of main is a good default. The program is about to exit anyway, and the warning disappears. For code that is part of a larger application, or a library other code calls into, avoid closing a scanner on System.in. You do not own the stream, and closing it affects every other caller.
If you choose not to close, say so in a comment. That tells the next reader the omission is deliberate.
import java.util.Scanner;
public class NoClose {
public static void main(String[] args) {
// Deliberately not closed: closing would also close System.in.
@SuppressWarnings("resource")
Scanner in = new Scanner(System.in);
System.out.print("Name: ");
System.out.println("Hello, " + in.nextLine());
}
}@SuppressWarnings("resource") silences the compiler lint warning that some IDEs and javac -Xlint report for unclosed resources.
Scanners on other sources should be closed
The concern above is specific to System.in, which you do not own. If a scanner reads from a file, you opened that file, so the scanner must close it. Here the close is required, not optional.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class FileSum {
public static void main(String[] args) throws FileNotFoundException {
int sum = 0;
try (Scanner in = new Scanner(new File("numbers.txt"))) {
while (in.hasNextInt()) {
sum += in.nextInt();
}
}
System.out.println("Sum: " + sum);
}
}If you skip the close, the operating system file handle stays open until the garbage collector finalizes the stream or the program exits. On a long-running program that opens many files, you will eventually hit the limit on open files.
Errors hidden inside a Scanner
A Scanner never throws IOException from its reading methods. If the underlying stream fails, the scanner catches the exception and acts as if the input has ended. To find out whether a failure caused that, call ioException() after the loop finishes. It returns the most recent IOException, or null if there was none.
import java.io.IOException;
import java.util.Scanner;
public class CheckFailure {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
while (in.hasNextLine()) {
in.nextLine();
count++;
}
IOException problem = in.ioException();
if (problem != null) {
System.err.println("Read failed: " + problem.getMessage());
} else {
System.out.println("Lines: " + count);
}
}
}This also helps you debug the closed-stream bug above. A scanner created on a closed System.in reports Stream closed through ioException().
Common errors and how to read them
| Symptom | Likely cause | Fix |
|---|---|---|
| `IllegalStateException: Scanner closed` | You called a reading method on a scanner after closing it, often because a helper closed a scanner that its caller still uses. | Close only where the scanner was created. |
| `NoSuchElementException: No line found` right after the first prompt | An earlier scanner closed `System.in`, or an earlier scanner buffered the input. | Use one shared scanner for the whole program. |
| Input typed by the user "disappears" only when piped | Two scanners on `System.in`, and the first one buffered everything. | Use one shared scanner. |
| IDE warning "Resource leak: 'in' is never closed" | The scanner is not closed. | Close it with try-with-resources, or suppress the warning with a comment explaining why. |
| Reads work, but a later `Console` or `BufferedReader` sees nothing | A scanner read ahead into its buffer, or closed `System.in`. | Do not mix input classes on the same stream. Pick one. |
The last row matters for the later chapters. Mixing Scanner with BufferedReader or with IO.readln on the same stream has the same buffering problem as mixing two scanners.
Summary of the working model
Scanner.close()marks the scanner closed and closes its source if the source isCloseable.System.inisCloseable, so closing a scanner on it closes the stream for the whole JVM.- A scanner on a closed stream behaves as if input has ended, so reads throw
NoSuchElementException. - A closed scanner itself throws
IllegalStateExceptionon every read. - Scanners buffer ahead, so two scanners on one stream can lose input even if nothing is closed.
- Create one scanner on
System.in, pass it to the code that needs it, and close it, if at all, only at the point where it was created. - Always close scanners on files or other resources you opened yourself.
Exercise
A program has a method static String ask(String prompt) that creates new Scanner(System.in) in a try-with-resources block, prints the prompt and returns in.nextLine(). The program calls ask("First: ") and then ask("Second: "). What happens on the second call, and how do you fix it?
Show answer
The first call closes the scanner, which also closes System.in. On the second call a new scanner reads from a closed stream, treats it as end of input, and nextLine throws NoSuchElementException with "No line found". The fix is to create one Scanner in main, change the method to ask(Scanner in, String prompt), pass the scanner in, and close it once at the end of main (or not at all, with a comment explaining why).
Exercise
What is the difference between the exceptions you get when you call nextInt() on a Scanner you have closed, and when you call nextLine() on a new Scanner built on a System.in that was closed earlier?
Show answer
Calling any reading method on a closed Scanner throws IllegalStateException with the message "Scanner closed", because that scanner object knows it was closed. A new Scanner on a closed System.in is itself open, but its source fails when read. The scanner treats the failure as end of input, so nextLine throws NoSuchElementException ("No line found"), while hasNextLine returns false. You can confirm the cause by calling ioException(), which returns the IOException reporting that the stream is closed.