How to Close a Scanner in Java: What Every Developer Should Know
Java's Scanner class is one of the most commonly used tools for reading input — whether from the keyboard, a file, or a string. But knowing how to properly close a Scanner is just as important as knowing how to open one. Leaving a Scanner open can cause resource leaks, unexpected behavior, and warnings from your IDE or static analysis tools.
Here's a clear breakdown of how closing a Scanner works, why it matters, and what factors shape the right approach for your situation.
What Closing a Scanner Actually Does
A Scanner object wraps an underlying input source — a stream, a file, or System.in. When you call .close(), the Scanner closes that underlying stream. This releases the operating system resources tied to the open stream and signals that your program is done reading from it.
In Java's resource management model, streams and readers fall under the Closeable interface. Failing to close them can leave file handles open, which is a problem in long-running applications or programs that open many files in sequence.
The Basic Way: Calling .close() Manually
The simplest approach is calling .close() directly on your Scanner instance when you're done with it: