/home/wpollock1/public_html/Java/ConsoleDemo.java

// ConsoleDemo - This class shows how to use a Console object for
// I/O.  Console is an  alternative to using System.in and System.out,
// but depending on how the program was run, there may be no console
// available.  Additionally, this code shows how to use Console to
// read in a password from a console program, which won't echo the
// password entered.
// The JVM throws an IO error if you try this with standard input
// redirected from someplace unreadable; try " ... < NUL" on Windows.
//
// Written 12/2012 by Wayne Pollock, Tampa Florida USA
// Based on the example code in the Java docs.

import java.io.Console;
import java.util.Arrays;

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

    Console con = System.console();
    if ( con == null )
      throw new UnsupportedOperationException( "No Console Available" );

    con.printf( "Username: " );
    String userName = con.readLine();  // doesn't include any EOL characters

    // Read in password, with no echo:
    final char [] enteredPassword = con.readPassword( "Password: " );

    if ( enteredPassword == null ) {
      con.printf( "Incorrect password\n" );
    } else {
      final char [] actualPassword = "secret".toCharArray();
      if ( Arrays.equals( actualPassword, enteredPassword ) )
        con.printf( "Welcome %s!%n", userName );
      else
        con.printf( "Incorrect password\n" );

      // In any case, need to erase the passwords from memory now:
      Arrays.fill( enteredPassword, '\0' );
      // This is pointless; *never* hardcode passwords in your code!
      Arrays.fill( actualPassword, '\0' );
    }
  }
}