Close a Scanner by calling the close() method
A Scanner in Java reads input from a source — usually the keyboard, a file, or a network connection. When you are done using it, you must close it. Closing a Scanner tells Java to release the resources it was using, which prevents memory leaks and file handle exhaustion.
The simplest way to close a Scanner is to call its close() method directly on the Scanner object. If your Scanner is named input, you write input.close(); on its own line. This works immediately and is the most straightforward approach.
However, there are two better patterns that handle errors automatically and are safer in real code: the try-with-resources statement and the try-finally block. Both ensure the Scanner closes even if an exception occurs while you are reading from it.
Key Takeaways
- Call close() on your Scanner object to release the resources it holds, or the program may run out of file handles or memory.
- Use a try-with-resources statement (Java 7 and later) to close the Scanner automatically without writing extra code.
- If you cannot use try-with-resources, wrap your Scanner code in a try-finally block and call close() in the finally section.
- Calling close() on a Scanner that reads from System.in will close System.in itself, which affects the entire program — avoid this unless you are certain you will not need keyboard input again.
Use try-with-resources for automatic closing
The try-with-resources statement is the modern way to handle Scanner closing. It automatically calls close() when the block exits, whether the code succeeds or throws an exception. This pattern is available in Java 7 and later.
The syntax looks like this:
try (Scanner input = new Scanner(System.in)) { String line = input.nextLine(); System.out.println(line); }
The Scanner is declared inside the parentheses after try. When the closing brace of the try block is reached, Java automatically calls input.close() for you. If an exception occurs inside the block, the Scanner still closes before the exception is thrown to the caller.
You can declare multiple resources in a single try-with-resources statement by separating them with semicolons. Each one will be closed in reverse order of declaration when the block exits.
Use try-finally if you cannot use try-with-resources
If your project uses Java 6 or earlier, or if you need more control over when closing happens, use a try-finally block. The finally section always runs, even if an exception occurs in the try section.
The pattern looks like this:
Scanner input = new Scanner(System.in); try { String line = input.nextLine(); System.out.println(line); } finally { input.close(); }
The Scanner is created before the try block. The finally block runs after the try block completes or throws an exception, and input.close() is called there. This ensures the Scanner closes no matter what happens inside the try block.
If you want to handle exceptions from the close operation itself, wrap the close() call in its own try-catch block inside the finally section. This is rarely necessary but matters in code that reads from files or network sockets.
What happens when you do not close a Scanner
If you create a Scanner and never close it, the underlying resource stays open. For a Scanner reading from System.in, this is usually harmless in a short program. For a Scanner reading from a file, leaving it open prevents other programs from modifying or deleting that file on some operating systems.
The real danger appears when your program creates many Scanners without closing them. The operating system limits how many file handles or connections a single process can hold open at once. If you hit that limit, new Scanner objects will fail to create, and your program will crash with an exception like "Too many open files."
In long-running applications like web servers or background services, unclosed Scanners accumulate over time and eventually exhaust the system's resources. Closing every Scanner you create is a habit that prevents this problem before it starts.
Closing a Scanner that reads from System.in
Calling close() on a Scanner that wraps System.in closes System.in itself, not just the Scanner. Once System.in is closed, the entire program cannot read from the keyboard anymore, even if you create a new Scanner later.
In most programs, you should not close a Scanner that reads from System.in unless you are absolutely certain the program will not need keyboard input again. If your program has multiple methods that each create their own Scanner from System.in, close only the last one, or use a single Scanner throughout the program and pass it as a parameter.
If you must close a Scanner that reads from System.in, do it only at the very end of your program, after all keyboard input is complete. Document this clearly in a comment so future readers understand why the close is there.
Closing a Scanner that reads from a file
Scanners that read from files should always be closed when you are done with them. Use try-with-resources whenever possible, because it handles closing automatically and is the clearest way to show that the file is only needed inside that block.
Here is the pattern for reading a file:
try (Scanner input = new Scanner(new File("data.txt"))) { while (input.hasNextLine()) { String line = input.nextLine(); System.out.println(line); } }
The Scanner is created with a File object inside the try-with-resources parentheses. When the block exits, the Scanner closes and the file is released. This pattern works the same way whether the loop completes normally or throws an exception.
Common mistakes when closing Scanners
One common mistake is declaring the Scanner outside the try block and forgetting to close it in a finally block. If you write Scanner input = new Scanner(System.in); before the try, you must add a finally block with input.close(); or the Scanner will not close.
Another mistake is closing the Scanner too early. If you close it inside a loop and then try to read from it again in the next iteration, you will get an exception. Declare the Scanner once before the loop, and close it only after the loop finishes.
A third mistake is catching an exception from close() and ignoring it. While rare, closing a file-based Scanner can throw an exception if the file system fails. In production code, log or handle these exceptions rather than silently swallowing them with an empty catch block.
Frequently Asked Questions
Do I need to close a Scanner if the program is about to end?
Technically no — the operating system reclaims all resources when the program exits. However, it is still good practice to close Scanners explicitly. This habit prevents bugs when you refactor code later, and it makes the code's intent clear to anyone reading it.
What is the difference between close() and closing in try-with-resources?
There is no difference in what happens — both call the same close() method. Try-with-resources just calls it for you automatically, so you do not have to remember to write it. This reduces the chance of accidentally leaving a Scanner open.
Can I close a Scanner multiple times?
Yes. Calling close() on an already-closed Scanner does nothing and does not throw an exception. This is why it is safe to call close() in a finally block even if an earlier exception already closed the Scanner.
What happens if close() throws an exception?
For Scanners reading from System.in or a string, close() almost never throws an exception. For file-based Scanners, it can throw an IOException if the file system fails. Catch IOException in your finally block or let it propagate to the caller, depending on how your program handles errors.
Should I close a Scanner if I am using it in a method that returns early?
Yes — use try-with-resources or try-finally to ensure the Scanner closes even if the method returns early. If you write return value; inside a try block, the finally block still runs before the method actually returns, so the Scanner closes.