$show=/label

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

SHARE:

A quick guide to close scanner in java. How to close scanner in java using Scanner.close() method.

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.




COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,21,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,32,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,135,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,7,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,127,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,113,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,29,String,61,String Programs,28,String Revese,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,24,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java Scanner.close() - How to Close Scanner in Java?
Java Scanner.close() - How to Close Scanner in Java?
A quick guide to close scanner in java. How to close scanner in java using Scanner.close() method.
https://1.bp.blogspot.com/-QL0s9I_39F4/YZkkfAT6cKI/AAAAAAAADhk/0XjN3r97sq47AGApu1aFWlPbW8UqUxBywCLcBGAsYHQ/w400-h279/Java%2BScanner.close%2528%2529%2B-%2BHow%2Bto%2BClose%2BScanner%2Bin%2BJava%253F.png
https://1.bp.blogspot.com/-QL0s9I_39F4/YZkkfAT6cKI/AAAAAAAADhk/0XjN3r97sq47AGApu1aFWlPbW8UqUxBywCLcBGAsYHQ/s72-w400-c-h279/Java%2BScanner.close%2528%2529%2B-%2BHow%2Bto%2BClose%2BScanner%2Bin%2BJava%253F.png
JavaProgramTo.com
https://www.javaprogramto.com/2021/11/java-scanner-close.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2021/11/java-scanner-close.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content