Directory Image
This website uses cookies to improve user experience. By using our website you consent to all cookies in accordance with our Privacy Policy.

How to Close Scanner in Java: A Brief Guide

Author: Sophia Robart
by Sophia Robart
Posted: Aug 10, 2025

The Java Scanner is a utility class provided in the java.util package is implemented in Java. It is a generic input data reader of a given source, and it is a handy utility that can be used to obtain input data from a source, whether it is a file, the keyboard (console), or even a string variable. It was added to versions of Java after 1.5, and it was introduced to make the user input handling simpler, as it has the ability to parse common primitive data types (String, int, double, etc).

A common practice with the Scanner class is to create a Scanner instance, which is connected to an input stream (most often System.in as input source). This is in order that programs can speak to the users, i.e., by taking in some input during the run. You can, as an example, utilize some of the methods, like nextInt(), nextLine(), or nextDouble(,) when you need to insert a definite type of information that is to be read aloud by the user.

In addition to console input, Scanner also allows reading from files or strings, and this is where Scanner can help in parsing data of many forms. It will split the input into tokens based on whitespace by default, allowing you to read through them one at a time.

Why Closing Scanner Matters?

The proper way to close Scanner in Java is necessary to ensure that you use up the minimum resources and avoid memory leaks. When creating a Scanner object, system resources like input streams are retained by it. Otherwise, not releasing these resources by closing Scanner can lead to your program (and other user processes) being as famished for memory as possible and slow down in the long run. It is of particular importance when working with large or long-term applications, as the leak of resources might accumulate and cause either a crash or the application to slow down.

The other important factor is the effect on the input streams, more so in the case where a Scanner is reading an input from System. in (the console input stream). When the Scanner is closed, the input stream underneath is also Java Scanner close() method. This implies that when you close one Scanner reading System. In other components of your program, you will not be able to read user input since the standard input stream closes. Thus, you have to take caution on the closure of such Scanners.

Failure to close a Scanner has the results of:

Leaks in memory occur because of unreleased resources.

  • The possibility of running out of system resources.
  • Unanticipated behavior or exceptions when the input stream is closed too soon by mistake or is reused in the wrong way.

To sum up, it is essential to close Scanner to ensure proper programming hygiene, management of memory, and input stability within Java-based applications.

How to close Scanner in Java?

You can call a close() method on your Scanner object to close a Scanner in Java; this can be in the form of scanner.close(). This releases the system resources (file handles or input streams) of the Scanner and can help to avoid its resource leaks. In order to make sure that resources of the Scanners are released, it is a general practice to close it every time when you no longer need it, that is usually at the end of your program or in a finally block in the case you are not assigning it in a try-with-resources statement. For example:

Scanner scanner = new Scanner(System.in);

// Use the scanner for input

scanner.close();

Reading a file or other resource with a Scanner without closing the Scanner could create memory leak or locks on files. Java 7 introduces a new structure, try-with-resources, whereby the Scanner will be closed automatically:

try (Scanner scanner = new Scanner(System.in)) {

// Read input

} // Scanner is closed automatically here

Note: Closing a Scanner associated with System.in will close the standard input stream, and no more console input is possible for the rest of the application. In this scenario, you can only close the Scanner when you know there is no further input that will be necessary.

Leaving Scanners open can be regarded as bad coding practice and has a potential negative effect on the performance of bigger and long-term running applications or producing exceptions.

What Common Errors and Exceptions Are Related to Closing Scanner?IllegalStateException: Scanner Closed

An attempt to use a Scanner object that has been closed results in the throwing of IllegalStateException. So what goes wrong, say, when you invoke any method like nextLine() or nextInt() on an empty scanner? Java throws this exception. It may happen when you shut down a Scanner and then later, by accident, attempt to reuse it in the rest of your program or even in the same code block.

Exception thrown:

java.lang.IllegalStateException: Scanner closed

NoSuchElementException: Input Stream Closed

When you create a new Scanner on an already closed source (like System. in) with an existing Scanner, the new Scanner will cause the instance of NoSuchElementException to be thrown when you want to read it. This is because when a Scanner, which is based on System.in is closed, then the underlying input stream is also closed; obviously, no additional input operations can be performed on any other existing Scanner objects that want to utilize the input stream.

Multiple Scanners on Same Input Source

Multiple Scanners reading the same input source (System.in in particular) and closing any Scanner will close the underlying stream of all. When System.in is closed, it will instantly produce all the runtime errors whenever a new Scanner is created. The most prudent approach would be to create a one-time Scanner to System.in and reuse it throughout your application, closing it only when input is no longer needed.

Alternatives to Scanner and Their Resource Management

There are a variety of subclasses of Scanner in Java, other than the Java Scanner class, that can read input; tradeoffs and resource management are different in each.

BufferedReader: BufferedReader with an InputStreamReader in it is a commonly applied solution that is mostly used when a large amount of input needs to be read in a fast manner. It can read whole lines (rather than a single character) and is therefore blazingly fast compared to Scanner because it can store an internal buffer of many characters, and also because reading whole lines reduces the parsing overhead significantly.

Resource management: BufferedReader is closeable, thus close() it to prevent an excursion or disposal of the resources like Scanner.

Console: The other class that has simple and easy-to-use methods is console, which has readLine() and readPassword() methods that read user inputs in an interactive way. It is especially useful when it is applied together with the applications working in a terminal, which it does not usually provide in IDEs.

Resource management: It does not need explicit closure of the standard input because it is handled in the JVM.

DataInputStream: DataInputStream, which, in its usage, is normally binary data, is able to read text through methods such as readLine(), which is now legacy.

Resource management: As with BufferedReader, when it is no longer required, then close it, preferably with the help of a try-with-resources.

Comparison: BufferedReader is great in terms of performance and when working with large data, but it does not provide parsing of primitives, and one must parse it manually using methods such as Integer.parseInt().

Do You Seek Assistance?

There are almost endless support services available to students who are reaching out to StudyUnicorn.com. The procedure is in real time: you will be able to get in touch with your chosen writer to give instructions regarding revisions, and you will be able to view your previous orders to make up your mind. StudyUnicorn.com has been renowned for producing original work without cases of plagiarism, as well as for meeting deadlines, even when the deadlines are imminent.

Java Coding Tips for Beginners
  • Java Basics: It is time to learn Java basics, including data types, operators, control statements, and object-oriented programming, before going to higher knowledge.
  • Make Names Readable: Always give meaningful names to the classes, methods, and variable names, and make them readable.
  • Formatting: Standard formatting (such as indenting and brace positioning) should be used to make your code easy to read and without defects.
  • Comment Sensibly: It is advisable to enter comments in a few words that are understandable to explain the sophisticated logic, though not comment on the type of code that is obvious.
  • Avoid Hardcode: Do not hardcode-it will be easier to change in the future-use variables or constants.
  • Perfect Error Handling: Learn the usage of try-catch blocks and learn how to recognize common exceptions.
  • Practices: Coding is like physical exercise; you should keep on doing it frequently to train your skills.
Conclusion

The use of a Scanner in Java requires proper closing to achieve good resource handling and avoid memory leaks. An application is more stable when the system streams require to be released efficiently and, therefore, using close () method or try-with-resources is one way of achieving this. Avoiding unforeseen stream closures and exceptions upon input is a consequence of being cautious concerning Scanners bound to System.in. The use of best practices in handling resources results in more reliable and cleaner Java programs.

About the Author

I’m Sophia Robart, and I bring over a decade of experience in software development to my work as a programming expert. With a PhD in Computer Science from Stanford University,

Rate this Article
Leave a Comment
Author Thumbnail
I Agree:
Comment 
Pictures
Author: Sophia Robart

Sophia Robart

Member since: Aug 07, 2025
Published articles: 1

Related Articles