Java Console readPassword() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 6+

Definition

In Java, console.readPassword() reads one line from the terminal with echoing turned off: nothing appears while the user types, not even asterisks. It returns a char[] without the line break, or null at the end of input.

A char[] is used instead of a String so you can overwrite the secret when you are done, for example with Arrays.fill(password, ' '). A String cannot be changed.

An instance method of the java.io.Console class, available since Java 6. You never create a Console yourself: get it with Console console = System.console(); after import java.io.Console;, and check it for null before calling console.readPassword(...).

Never hard-code real passwords.

The login example compares against a demo value in the code only to show the comparison. Real programs check a salted hash stored elsewhere and never print or log a password.

Syntax

Same two forms as readLine, but the result is a char[]:

Java
Console console = System.console();
char[] pw = console.readPassword();                        // no prompt
char[] pin = console.readPassword("PIN for %s: ", "ana");  // formatted prompt
// ... check the characters ...
Arrays.fill(pw, ' ');                                      // wipe when done
CallWhat it does
console.readPassword()Reads hidden input with no prompt.
console.readPassword("Password: ")Prints the prompt, then reads hidden input.
Arrays.equals(typed, expected)Compares two char arrays element by element.
Arrays.fill(typed, ' ')Overwrites the secret once it is no longer needed.

Available since Java 6. Echo is switched back on after the user presses Enter, and the cursor moves to a new line, so the next output starts on its own line.

Library declarations
Java
// java.io.Console
public char[] readPassword()
public char[] readPassword(String fmt, Object... args)

Parameters

ParameterDescription
fmt (optional)Prompt format string, such as "Password: ".
args (optional)Values for the specifiers in fmt.

Return Value

Return ValueDescription
char[]The characters typed, without the line break. An empty array if the user pressed Enter straight away.
nullThe end of input was reached.

Compare with Similar Methods

Reading secrets versus normal input:

MethodHow it differs
readLine()Visible typing; returns a String.
Scanner.nextLine()Shows the typed text; never use it for passwords.
Arrays.fill()Overwrites the returned char[] when you are done.
reader()Raw Reader; does not hide input.

Java Examples

Example 1 — A Demo Login with a Hidden Password

Read a visible username and a hidden password, compare the password with a demo value, and wipe both arrays. The correct demo password is open123.

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

public class ConsoleReadPasswordLogin {
    public static void main(String[] args) {
        Console console = System.console();
        if (console == null) {
            System.out.println("No console available. Run this program from a terminal.");
            return;
        }
        char[] demoSecret = "open123".toCharArray();   // demo only: never hard-code real passwords
        String user = console.readLine("Username: ");
        if (user == null) {
            return;
        }
        char[] password = console.readPassword("Password for %s: ", user);
        if (password == null) {
            return;
        }
        boolean ok = Arrays.equals(password, demoSecret);
        Arrays.fill(password, ' ');
        Arrays.fill(demoSecret, ' ');
        if (ok) {
            console.printf("Welcome, %s!%n", user);
        } else {
            console.printf("Wrong password for %s.%n", user);
        }
    }
}

How It Works

  1. Visible, then hidden. The username is read with readLine; readPassword("Password for %s: ", user) puts the name into the prompt and shows no characters while the password is typed.
  2. Compare arrays, not strings. Arrays.equals checks the length and every character: the demo password gives true, and any other entry would print "Wrong password for alice."
  3. Wipe before replying. Both arrays are overwritten with spaces right after the comparison, so the secret is gone before the welcome or error message is printed.

Example 2 — Set a New Password: Minimum Length and Confirmation

Ask for a new password twice, require at least 8 characters, and allow three attempts.

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

public class ConsoleReadPasswordConfirm {
    public static void main(String[] args) {
        Console console = System.console();
        if (console == null) {
            System.out.println("No console available. Run this program from a terminal.");
            return;
        }
        for (int attempt = 1; attempt <= 3; attempt++) {
            char[] first = console.readPassword("New password (8+ characters): ");
            if (first == null) {
                return;
            }
            char[] second = console.readPassword("Type it again: ");
            if (second == null) {
                Arrays.fill(first, ' ');
                return;
            }
            boolean longEnough = first.length >= 8;
            boolean same = Arrays.equals(first, second);
            Arrays.fill(first, ' ');
            Arrays.fill(second, ' ');
            if (longEnough && same) {
                console.printf("Password changed on attempt %d.%n", attempt);
                return;
            }
            console.printf(longEnough ? "The entries do not match.%n" : "Too short, use at least 8.%n");
        }
        console.printf("Too many attempts. Password not changed.%n");
    }
}

How It Works

  1. Stop cleanly at end of input. A null first read returns at once; a null second read wipes the first array before returning.
  2. Decide, then wipe. The length check and Arrays.equals results go into two booleans, so both arrays are overwritten before a message is chosen.
  3. Up to three tries. Attempt 1 is too short, attempt 2 has two different entries, and attempt 3 passes both checks, so the loop returns with a success message; a fourth try is never offered.

Example 3 — Validate a PIN and Show Only Asterisks

readPassword shows nothing while typing. Afterwards, print one * per character so the user can see the length without seeing the PIN.

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

public class ConsoleReadPasswordPin {
    public static void main(String[] args) {
        Console console = System.console();
        if (console == null) {
            System.out.println("No console available. Run this program from a terminal.");
            return;
        }
        char[] pin = console.readPassword("Choose a 4-digit PIN: ");
        if (pin == null) {
            return;
        }
        boolean valid = pin.length == 4;
        for (char c : pin) {
            if (c < '0' || c > '9') {
                valid = false;
            }
        }
        char[] stars = new char[pin.length];
        Arrays.fill(stars, '*');
        console.printf("You typed %s (%d characters).%n", new String(stars), pin.length);
        console.printf(valid ? "PIN saved.%n" : "A PIN must be exactly 4 digits.%n");
        Arrays.fill(pin, ' ');
    }
}

How It Works

  1. Two rules. valid starts as pin.length == 4, and the loop sets it to false for any char outside '0' to '9', so the 3-character entry with a letter fails both.
  2. Safe feedback. A second array of the same length is filled with '*', and only that array is turned into a String and printed.
  3. Clean up last. After the messages, Arrays.fill(pin, ' ') replaces the real digits in memory.

Frequently Asked Questions

No. Echo is turned off completely, so nothing appears while the user types. If you want to show the length afterwards, print your own asterisks.
A char array can be overwritten with Arrays.fill when you are done. A String cannot be changed and may stay in memory until garbage collection.
For a demo, use Arrays.equals(typed, expected). Real programs compare salted hashes. Never convert the array to a String or print it.
Hidden input needs a real terminal, and many IDE run windows are not one. Run the program from a terminal with java ClassName, and always handle the null case.
null, for example when the user presses Ctrl+D on macOS or Linux, or Ctrl+Z then Enter on Windows.

Next: reader()

Get the console Reader to wrap in a Scanner or BufferedReader.

reader() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful