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.
Syntax
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.
Example
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:
Create a new object sc of the Scanner Class and pass the string stg to it as an argument:
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:
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.
Conclusion
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.