Read and display username & password with console

Q. Write a program to read the username and password from the user and display them using Console class.

Answer:

Console Class:
Console class provides the method to access the character based console device. If any application needs to read the password or other secure data, then we use the console class.

Here, we read the username and password from the user and print them on console. The readPassword () method used to read the password from the user and it doesn’t show at time of entering.

ConsoleTest.java

import java.io.Console;
public class ConsoleTest
{
     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:

console