Your Guide to How To Close Scanner In Java
What You Get:
Free Guide
Free, helpful information about Internet & Networking and related How To Close Scanner In Java topics.
Helpful Information
Get clear and easy-to-understand details about How To Close Scanner In Java topics and resources.
Personalized Offers
Answer a few optional questions to receive offers or information related to Internet & Networking. The survey is optional and not required to access your free guide.
How to Close a Scanner in Java (And Why It Matters)
If you've written Java programs that read input — from the keyboard, a file, or a network stream — you've almost certainly used the Scanner class. Knowing how to properly close a Scanner is one of those small habits that separates clean, reliable code from programs that silently leak resources or throw unexpected errors.
What Is a Scanner and Why Does Closing It Matter?
The Scanner class in Java (java.util.Scanner) is a utility for parsing input from various sources: System.in, File objects, InputStreams, Strings, and more. Under the hood, a Scanner wraps a readable resource — and when that resource is an open stream or file, it holds onto system-level handles until explicitly released.
Failing to close a Scanner can lead to:
- Resource leaks — open file handles that persist until the JVM shuts down
- Locked files — on some operating systems, an unclosed file-backed Scanner can prevent other processes from accessing that file
- Compiler warnings — many IDEs flag unclosed Scanner instances as a potential issue
- Unexpected behavior — in long-running applications, accumulated unclosed streams can exhaust available file descriptors
For simple console programs, the JVM will clean up on exit anyway. But for anything reading files, sockets, or running in a server context, closing properly is essential.
The Basic Way to Close a Scanner 🔒
Closing a Scanner is straightforward. The class implements Closeable, which means it has a .close() method: