Console Class and Scanner Class in Java

Console Class

Console class provides the method to access the character based consol device. If any application needs to read the password or other secure data, then we use the console class. It is subclass of Object class and implements the flushable interface.

Example: Getting the user inputs using Console class

// ConsoleDemo.java
import java.io.Console;
public class ConsoleDemo
{
   public static void main(String[] args) throws Exception
   {
        Console console = System.console();
        if (console == null)
       {
            System.out.println("Unable to fetch console");
            return;
        }
        System.out.print("Enter username:");
        String user = console.readLine();

        System.out.print("Enter password:");
        char ch[] = console.readPassword();
        String password = String.valueOf(ch);

        System.out.println("Username: "+user);
        System.out.println("Password:"+password);
    }
}


Output:
Enter username:SurenDra
Enter password:
Username: SurenDra
Password: 123456

Scanner Class


It is used to read the input from the keyboard. Java Scanner class extends the Object class and implements Iterator and Closable interface. It is present in java.util package. A Scanner breaks its input into token using delimiter pattern.

For example:
Scanner sc = new Scanner (System. in);
int a = sc.nextInt();

Scanner Class Methods

MethodsReturn
int nextInt()It scans the next token of the input as an int. if the input is not an Integer it throws an exception.
long nextLong()It scans the next token of the input as a long value.
float nextFloat()It scans the next token of the input as a float value.
double nextDouble()It returns the next token as a double value.
String next()It returns the next complete token from the scanner as a string.
String nextLine()If the scanner has an input at another line, it returns true, otherwise false.
boolean hasNextInt()If the next token of the Scanner has an int value, it returns true.
boolean hashNextFloat()If the next token of the Scanner has a float value, it returns true.
void close()This method is used for close the Scanner.

Example: Getting user input using Scanner class in Java.

// ScannerDemo.java
import java.util.Scanner;
public class ScannerDemo
{
    public static void main(String args[])
    {
      Scanner scn = new Scanner(System.in);
      System.out.print("Enter first number: ");
      int a = scn.nextInt();
      System.out.print("Enter second number: ");
      int b = scn.nextInt();
      int result = a + b;
      System.out.println("Sum of given number: "+result);
      scn.close();
   }
}


Output:
Enter first number: 50
Enter second number: 90
Sum of given number: 140