Java implementation of Scanner close method
In the following program, a Scanner object closed and once it closed a System stream cannot be re-opened. Hence, after entered string, the control directly printed the default value of int n=0.
Codeaft.java
import java.util.Scanner;
class Codeaft
{
    public void action()
    {
        stringScanner();
        intScanner();
    }
    
    public void stringScanner()
    {
        String s="";
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter the string ");
        if(sc.hasNext())
        {
            s=sc.nextLine();
        }
        sc.close();
        System.out.println("\nString "+s);
    }
    
    public void intScanner()
    {
        int n=0;
        Scanner sc=new Scanner(System.in);
        System.out.print("\nEnter the number ");
        if(sc.hasNext())
        {
            n=sc.nextInt();
        }
        sc.close();
        System.out.println("\nNumber "+n);
    }
    
    public static void main(String args[])
    {
        System.out.println("———————————————————————————————————————————");
        System.out.println("Java implementation of Scanner close method");
        System.out.println("———————————————————————————————————————————");
        Codeaft c=new Codeaft();
        c.stringScanner();
        c.intScanner(); 
        System.out.println("———————————————————————————————————————————");
    }
}
Output
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft ——————————————————————————————————————————— Java implementation of Scanner close method ——————————————————————————————————————————— Enter the string CODEAFT String CODEAFT Enter the number Number 0 ——————————————————————————————————————————— codeaft@codeaft:~$
Example 2: Java implementation of Scanner close method
Codeaft.java
import java.util.Scanner;
class Codeaft
{
    public static void main(String args[])
    {
        String s="Hello, World!";
        Scanner sc=new Scanner(s);
        System.out.print(sc.nextLine());
        sc.close();
        System.out.println("\n\nScanner closed");     
    }
}
Output
codeaft@codeaft:~$ javac Codeaft.java
codeaft@codeaft:~$ java Codeaft Hello, World! Scanner closed codeaft@codeaft:~$
Comments and Reactions