CKTIS / Java
Closing a scanner: Scanner.close()
`Scanner.close()` closes a scanner and can also close its input source. Learn when to call it and why shared standard input needs special care.
Version: Java SE 21
Syntax
public void close()
scanner.close();In Java SE 21, Scanner.close is an instance method of java.util.Scanner. Call scanner.close() when you are done using that scanner. It takes no arguments, returns no value, and declares no checked exceptions. Calling it again has no effect.
Once the scanner is closed, scanning methods such as next() and hasNext() throw IllegalStateException. This is not the same as reaching the end of input: hasNext() returns false on an open scanner with no next token.
On the first close, the scanner also calls close() on its underlying Readable if that object implements java.io.Closeable. Closing a scanner created with new Scanner(System.in) passes the close() call on to the stream that System.in referred to when the scanner was created. The effect depends on how that stream implements close(). Do not close that scanner while another part of the program still needs that stream.
When your code is responsible for closing a resource managed by the scanner, such as a file opened for the current task, use try-with-resources. Java calls close() when the block exits, even if it exits because of an exception.
Examples
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner("alpha beta");
System.out.println(scanner.next());
scanner.close();
scanner.close();
try {
scanner.hasNext();
} catch (IllegalStateException e) {
System.out.println("IllegalStateException");
}
}
}Result
alpha IllegalStateException
The scanner reads a fixed string, not `System.in`. The program prints `alpha`, calls `close()` twice, and catches the exception from `hasNext()` even though `beta` was never read.
Related lessons
- Java · Lesson 2 · Basic · Version: 2