Table of content

How to close scanner in Java

The close() method of java.util.Scanner class is used to close the scanner. If the scanner is already closed then invoking this method will have no effect.

If the scanner is not closed then if its readable also implements the closeable interface then the readable's close method will be invoked.

If the user does not close the Scanner then the Java will not garbage collect the Scanner object which will lead to a memory leak in the program.

If the user tries to use the Scanner after closing, an IllegalStateException is thrown.

import java.util.Scanner;
public class Example {
  public static void main(String args[]) {
    String s = "Java is a object oriented programming";
    Scanner sc = new Scanner(s);
    System.out.println("" + sc.nextLine());
    //Close the scanner
    sc.close();
    System.out.println("Scanner Closed.");
  }
}

The output is

Java is a object oriented programming
Scanner Closed.

Another way to close the scanner automatically is using try-with-resources. When we use try-with, it automatically closes the underlying Scanner, which automatically closes the underlying stream that is System.in.

import java.util.Scanner;
public class Example {
  public static void main(String args[]) {
    String s = "Cloud Computing";
    try (Scanner sc = new Scanner(s)) {
      System.out.println("" + sc.nextLine());
      System.out.println("Scanner Closed");
    }
  }
}

The output is

Cloud Computing
Scanner Closed
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions