Java Utility Library

Java Scanner - close() Method



The java.util.Scanner.close() method is used to close the scanner. 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. If this scanner is already closed then invoking this method will have no effect.

Syntax

public void close()

Parameters

No parameter is required.

Return Value

void type.

Exception

Throws IllegalStateException, if the search operations is attempted after a scanner has been closed.

Example:

In the example below, the java.util.Scanner.close() method is used to close the specified scanner.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {

    //String to scan
    String MyString = "Hello World \nLearn Programming";

    //creating a Scanner
    Scanner MyScan = new Scanner(MyString);

    //print the next line of the scanner
    System.out.println(MyScan.nextLine());
    
    //close the scanner
    MyScan.close();
    System.out.println("Scanner is closed.");   
  }
}

The output of the above code will be:

Hello World 
Scanner is closed.

❮ Java.util - Scanner