Question and Answer

how to close a scanner in java

In this tutorial, you will learn how you can close a scanner in java. The close() method is  used  for Java Scanner class that uses to closes this scanner.

 

The java.util.Scanner class’s close() method closes the scanner that has been opened. This method will have no effect if the scanner is already closed when it is called.

 

syntax:

				
					public void close()
				
			

Example 1:

				
					import java.util.Scanner;    
public class ScannerCloseExample1{    
   public static void main(String args[]){    
    String s = "Hi All! This is Programiz.xyz.";  
      //Create a scanner with 
      
      Scanner scanner = new Scanner(s);  
      System.out.println("" + scanner.nextLine()); 
      
      //Close the scanner  
     
      System.out.println("Closing the Scanner...");  
      scanner.close();  
      System.out.println("Scanner is Closed.");  
   }    
}     
				
			

Output:

				
					Hi All! This is programiz.xyz.
Closing the Scanner...
Scanner is Closed.
				
			

Example 2:

				
					import java.util.Scanner;    
public class ScannerCloseExample2{    
   public static void main(String args[]){   
     System.out.print("Enter Your Father's Name: "); 
     
       //Create a scanner 
       
       Scanner scanner = new Scanner(System.in);      
       String name = scanner.next();  
       System.out.println("Name: "+name);   
       //Close the scanner  
       scanner.close();  
       System.out.println("Scanner is Closed.");  
   }    
}    
				
			

Output:

				
					Enter Your Father's Name: MD. MOZAMMEL HAQUE
Name: JavaTpoint
Scanner is Closed.
				
			

Example 3:

				
					package xyz.programiz;

import java.util.*;

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

      String s = "Hello universe! 3 + 3.0 = 6";

    
      Scanner scanner = new Scanner(s);

    
      System.out.println("" + scanner.nextLine());

    
      System.out.println("Closing the Scanner...");
      scanner.close();
      System.out.println("Scanner is Closed.");
   }
}
				
			

Output:

				
					Hello Universe! 3 + 3.0 = 6
Closing the Scanner...
Scanner is Closed.
				
			

Return Value: There is no value returned by this function.

In this tutorial, you can learn how you can close a scanner in java. Hope you enjoy this tutorial. 

 

Related Articles