Pages

Saturday, November 20, 2021

Java Scanner.close() - How to Close Scanner in Java?

1. Overview

In this article, We'll learn how to close the scanner in java and what are the best practices to do it.

Java Scanner.close() - How to Close Scanner in Java?


2. Java Scanner.close() 


look at the below syntax.

Syntax:
public void close()

close() method does not take any arguments and returns nothing. It just closes the current scanner instance.


If this scanner has not yet been closed then if its underlying readable also implements the Closeable interface then the readable's close method will be invoked.

Invoking this method will have no effect if the scanner is already closed.

An IllegalStateException will be thrown if you attempt to execute search activities after a scanner has been closed.

3. How to close scanner in java?


Once you perform the operations on Scanner instance then at the end you need to close the scanner properly. Otherwise, scanner will be opened and it is available to pass any info to the application and may cause the data leaks.

It is always recommended to close the resources in the recommended way.

Example 1:

In the below example, we are reading two values from the user and then closing the scanner after completing the actions on it.
package com.javaprogramto.programs.scanner.close;

import java.util.Scanner;

public class ScannerCloseExample1 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		System.out.println("Enter your birth year");
		int year = scanner.nextInt();

		System.out.println("Enter your age ");
		int age = scanner.nextInt();

		scanner.close();

		System.out.println("Given age and year are (" + age + "," + year + ")");
	}
}

Output:
Enter your birth year
1990
Enter your age 
31
Given age and year are (31,1990)

4. Read values after Scanner close() invocation


After closing the Scanner with the close() method, then next invoke next() method.
What is your expected output?

Example 2:
package com.javaprogramto.programs.scanner.close;

import java.util.Scanner;

public class ScannerCloseExample2 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);

		System.out.println("Enter your birth year");
		int year = scanner.nextInt();

		System.out.println("Enter your age ");
		int age = scanner.nextInt();

		scanner.close();

		System.out.println("Given age and year are (" + age + "," + year + ")");
		
		System.out.println("Enter your name ");
		String name = scanner.next();
	}
}

Output:
Enter your birth year
2000
Enter your age 
21
Given age and year are (21,2000)
Enter your name 
Exception in thread "main" java.lang.IllegalStateException: Scanner closed
	at java.base/java.util.Scanner.ensureOpen(Scanner.java:1150)
	at java.base/java.util.Scanner.next(Scanner.java:1465)
	at com.javaprogramto.programs.scanner.close.ScannerCloseExample2.main(ScannerCloseExample2.java:21)


Execution is failed at runtime because it is saying IllegalStateException with the reason scanner is closed already. 

Here, we tried to read the name string from the user after closing the connection with scanner.

5. Closing Scanner From Finally Block


It is a better approach to close the finally always from the finally block. If there is an exception then it must be closed before the error.

If you read the data from the file or string with multi-line separators, you must have to close the scanner.

Example 3:

Closing scanner from finally block.
package com.javaprogramto.programs.scanner.close;

import java.util.Scanner;

public class ScannerCloseExample2 {

	public static void main(String[] args) {

		String multiLinesSeparator = "Line 1 \n Line 2 \n Line 3";
		Scanner scanner = new Scanner(multiLinesSeparator);

		try {

			String firstLine = scanner.nextLine();
			String secondLine = scanner.nextLine();
			String thirdLine = scanner.nextLine();

			System.out.println(
					"Info from string via scanner are (" + firstLine + ", " + secondLine + ", " + thirdLine + ")");

			thirdLine.charAt(100);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			scanner.close();
            System.out.println("scanner is closed");
		}

	}
}

Output:
Info from string via scanner are (Line 1 ,  Line 2 ,  Line 3)
java.lang.StringIndexOutOfBoundsException: String index out of range: 100
	at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:48)
	at java.base/java.lang.String.charAt(String.java:711)
	at com.javaprogramto.programs.scanner.close.ScannerCloseExample2.main(ScannerCloseExample2.java:21)
scanner is closed

Scanner is closed even though an exception is thrown.


6. Conclusion


In this article, we've seen how to close scanner in java using Scanner.close() method.
Scanner can be used to read the input from the user, string or file. For all sources, we need to close the scanner always.




No comments:

Post a Comment

Please do not add any spam links in the comments section.