How to Close Scanner in Java | Studyunicorn.com
When learning Java, one of the most common classes beginners use is the Scanner class, which allows programs to take input from the user. Whether you’re reading integers, strings, or floating-point numbers, the Scanner class makes handling input simple. However, a common question arises among new programmers: How to close Scanner in Java?
Why Closing Scanner is Important
In Java, the Scanner class is often used to read input from the System.in stream. While it may not always cause immediate issues, failing to close a Scanner can lead to resource leaks. This means your program continues to hold onto system resources even after you’re finished using them, which is not good practice.
Closing a Scanner helps:
Free up system resources.
Prevent potential memory leaks.
Improve efficiency in larger applications.
How to Close Scanner in Java
Closing a Scanner is simple. Once you are done reading input, call the .close() method.
Here’s a quick example:
import java.util.Scanner; public class CloseScannerExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter your name: "); String name = sc.nextLine(); System.out.println("Hello, " + name + "!"); // Closing the scanner sc.close(); } }
In the above program, the Scanner object sc is used to read input, and once finished, we call sc.close() to properly close it.
Important Things to Remember
Do not close Scanner too early – If you close it before finishing input, you won’t be able to read additional data.
Avoid multiple closures of System.in – Once a Scanner tied to System.in is closed, you cannot reopen it in the same program run.
Best practice – Close the Scanner at the end of your program, usually in the finally block or after all input is read.
Final Thoughts
Understanding how to close Scanner in Java is part of writing clean, efficient code. At Study unicorn, we guide students and beginners through Java fundamentals with easy explanations and practical examples. By managing resources properly, you’ll not only avoid errors but also develop professional coding habits that serve you well in advanced projects.
Also read more:
ore
100 reasons why homework should be banned



This is a really clear explanation of how ToothfairyAI provides expert AI agents in Australia, helping businesses.