Scanner close() method in Java with Examples
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:
// Java program to illustrate the // close() method of Scanner class in Java import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Get the string String s = "Geeksforgeeks has Scanner Class Methods"; // create a new scanner // with the specified String Object Scanner scanner = new Scanner(s); // print the next line of the string System.out.println("Scanner: " + scanner.nextLine()); // close the scanner scanner.close(); System.out.println("\nScanner Closed.\n"); System.out.println("Trying to use scanner" + " after closing."); // print the next line of the string System.out.println(scanner.nextLine()); } catch (Exception e) { System.out.println("Exception thrown:\n" + e); } } } |
chevron_right
filter_none
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()
Recommended Posts:
- Scanner useDelimiter() method in Java with Examples
- Scanner locale() method in Java with Examples
- Scanner useLocale() method in Java with Examples
- Scanner nextFloat() method in Java with Examples
- Scanner delimiter() method in Java with Examples
- Scanner hasNextFloat() method in Java with Examples
- Scanner useRadix() method in Java with Examples
- Scanner reset() method in Java with Examples
- Scanner nextInt() method in Java with Examples
- Scanner nextByte() method in Java with Examples
- Scanner nextBigInteger() method in Java with Examples
- Scanner nextShort() method in Java with Examples
- Scanner nextLong() method in Java with Examples
- Scanner nextLine() method in Java with Examples
- Scanner nextBigDecimal() method in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



