The close() method ofjava.util.Scanner class closes the scanner which has been opened. If the scanner is already closed then on calling this method, it will have no effect.
Syntax:
public void close()
Return Value: The function does not return any value.
Below programs illustrate the above function:
Program 1:
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
String s = "Geeksforgeeks has Scanner Class Methods" ;
Scanner scanner = new Scanner(s);
System.out.println( "Scanner: "
+ scanner.nextLine());
scanner.close();
System.out.println( "\nScanner Closed.\n" );
System.out.println( "Trying to use scanner"
+ " after closing." );
System.out.println(scanner.nextLine());
}
catch (Exception e) {
System.out.println( "Exception thrown:\n" + e);
}
}
}
|
Output:
Scanner: Geeksforgeeks has Scanner Class Methods
Scanner Closed.
Trying to use scanner after closing.
Exception thrown:
java.lang.IllegalStateException: Scanner closed
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#close()