Java I/O How to - Read username and password via Console class


We would like to know how to read username and password via Console class.


//from   w w  w.  java  2s.c  o  m
import java.util.Arrays;

public class Main {

  public static void main(String[] args) {
    Console console = System.console();
    String username = console.readLine("Username: ");
    char[] password = console.readPassword("Password: ");

    if (username.equals("admin") && String.valueOf(password).equals("secret")) {
      console.printf("Welcome to Java Application %1$s.\n", username);

      Arrays.fill(password, ' ');
    } else {
      console.printf("Invalid username or password.\n");

The code above generates the following result.