How to Close a Scanner in Java

Java Scanner is a class used to read data from files, strings, and users. This class belongs to the java.util package. More specifically, the close() method of the Scanner class is used to close the opened Scanner object. It is recommended to close the Scanner after performing any tasks on the Scanner instance; otherwise, the Scanner will be activated and potentially cause data leaks.

This article will discuss how to close a scanner in Java with a detailed example.

How to Close a Scanner in Java?

In Java, the close() method of the Scanner class is utilized for closing a Scanner. This method accepts no arguments and returns nothing. It just terminates the current Scanner instance.


The syntax of the close() method is given as:


Here, sc is an instance of the Scanner class that invokes the close() method.

Note: If the Scanner has already been closed, the close() method will not perform any operation. Similarly, after closing the Scanner, if you want to access something or execute some lines of code, it will throw an IllegalStateException.


In this example, we will print out a string using the Scanner class, then close the Scanner using the close() method, and again try to print another string which will throw an exception.

First, we will store a string in the variable stg. Here \n indicates a new line:

String stg = " Hello! This is my details: \n Name= John \n Age= 34 \n City=London";

Create a new object sc of the Scanner Class and pass the string stg to it as an argument:

Scanner sc = new Scanner(stg);

Print the string by using the nextLine() method with object sc. This method will detect a new line, move to that line, and then print it. We call the nextLine() method four times to print all the lines of the string stg:


After printing the string, we will close the Scanner object sc by using the close() method:


After closing the Scanner, we will again create one more string named stg1 and execute it by using the same object sc:

String stg1 = "Phone #: 090078601";

The given output indicates that we have successfully closed the Scanner at first, and re-accessing it throws an IllegalStateException:

We have provided the guidelines related to closing a Scanner in Java.


To close a Scanner in Java, you can use a close() method of the Scanner class. This method takes no arguments, returns nothing, and terminates the current Scanner instance. To utilize the close() method, create an object of the Java Scanner class and invoke the close() method with it. Also, re-accessing a closed Scanner throws an IllegalStateException. This article discussed the procedure of closing a Scanner in Java.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.