Colin O'Croidheagain Colin O'Croidheagain - 1 year ago 124
Java Question

Hide Password From Console Window Java Asterisk Password Or Block Inputted String Being Displayed

public class Login {

protected static String user, pass, host;
Object conn;

public void Login() throws SQLException

try {
Class.forName ("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println ("Could not load the driver");

Scanner sc = new Scanner(;
Console console = System.console();

System.out.println("Please Enter Username");
user =;
System.out.println("Please Enter Password");
pass = sc.nextLine();
System.out.println("Please Enter Host/IP Address");
host =;
System.out.println("Attempting Log In");

Connection conn = (Connection) DriverManager.getConnection
("jdbc:mysql://"+host+":3306/chessdb", user, pass);

Just bit of help, been looking around online at blocking the password being shown on the console window. Is there a simple method of either the inputted text not appearing at all or else an asterisk to cover the input of the password field only?

Answer Source

Use the readPassword() method.

instead of using scanner like

System.out.println("Please Enter Password");
    pass = sc.nextLine();


    System.out.println("Please Enter Password");
    char[] passString = Console.readPassword();
    String pass = new String(passString );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download