Sub topic 10
java.io.Console and passwords
This chapter assumes you can read lines with Scanner (see the earlier chapters on Scanner, the leftover newline, and end of input). It also assumes you can compile and run a Java program from a terminal and that you know how try/finally works. The chapter covers java.io.Console, the class for talking to a person at a terminal. It also covers its one feature Scanner lacks: reading a password without echoing it.
What Console is
java.io.Console represents the terminal a program was started from. You don't construct it. You ask for it:
Console console = System.console();A Console offers four groups of methods:
| Method | Purpose |
|---|---|
| `readLine()` and `readLine(String fmt, Object... args)` | Print an optional prompt, then read one line as a `String`. |
| `readPassword()` and `readPassword(String fmt, Object... args)` | Print an optional prompt, then read one line with echo turned off, returned as a `char[]`. |
| `printf(...)` and `format(...)` | Write formatted text to the terminal. |
| `reader()` and `writer()` | Give access to a `Reader` and `PrintWriter` on the terminal. |
Console is not AutoCloseable. You don't close it, and there is no System.in ownership problem like the one a Scanner has.
Why the prompt is part of the call
With Scanner you print a prompt with System.out.print and then read. Console.readLine takes the prompt as an argument. For readPassword this matters. The prompt is printed, echo is switched off, the line is read, and echo is switched back on, all inside one call. If you print the prompt yourself, nothing is wrong, but the combined form keeps the steps together.
The prompt is a format string, as in String.format. This has a consequence.
console.readLine("Discount (%): "); // throws an exception
console.readLine("Discount (%%): "); // prints: Discount (%):
console.readLine("%s", "Discount (%): "); // safe for any textA lone % is parsed as a format specifier and the call throws a java.util.IllegalFormatException subclass. If the prompt contains text you did not write, such as a file name or a user name, pass it as an argument to %s.
The basic login example
import java.io.Console;
import java.util.Arrays;
public class Login {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.err.println("No console available");
return;
}
String user = console.readLine("User: ");
char[] password = console.readPassword("Password: ");
System.out.println("Hello, " + user);
Arrays.fill(password, ' ');
}
}Run it from a terminal with javac Login.java and java Login. The user name appears as you type it. The password characters do not appear at all, not even as asterisks.
This version has a flaw that the next sections fix: readLine and readPassword return null when the input ends, so Arrays.fill(password, ' ') would throw a NullPointerException if the user pressed Ctrl+D (Ctrl+Z then Enter on Windows) at the password prompt.
When System.console() returns null
System.console() returns null when the JVM has no console. In older Java versions this happens whenever standard input or standard output is not attached to an interactive terminal:
- You run the program from an IDE's built-in run window.
- You redirect input:
java Login < answers.txt. - You pipe input:
echo alice | java Login. - The program runs as a background service or in a CI job.
Many beginners see "No console available" for the first time when they click Run in an IDE, not because the code is wrong.
Recent JDKs changed this. Starting with Java 22, Console gained an isTerminal() method. The JDK can then return a Console object even when the streams are redirected, so a non-null result no longer proves that a person is typing. The exact default depends on the JDK version and the jdk.console system property, so check the release notes of the version you target. A check that works on both old and new JDKs looks like this (it needs Java 22 or later to compile because of isTerminal):
import java.io.Console;
public class ConsoleCheck {
public static void main(String[] args) {
Console console = System.console();
if (console == null || !console.isTerminal()) {
System.err.println("Run this program in an interactive terminal.");
return;
}
System.out.println("Interactive terminal detected.");
}
}If you must compile for Java 21 or earlier, use only the null check.
The flow below shows the decision.
Why readPassword returns char[]
A String is immutable. Once created, its characters stay in memory until the garbage collector reclaims the object, and you cannot overwrite them. A secret held in a String may remain in memory (and in heap dumps or swap files) for an unpredictable time.
A char[] can be overwritten. After you have used the password, fill the array with a dummy value. This is why readPassword returns char[], and why converting it with new String(password) throws away the benefit.
This does not make the program safe against an attacker who already controls the machine. It reduces the time a plain-text password lives in memory and keeps it out of accidental logs and string pools. Treat it as hygiene, not as a security boundary.
A complete example with null handling and wiping
This program asks for a new password twice, compares the arrays, and wipes both in a finally block. It uses Arrays.equals for the comparison, because == and equals on an array compare references, not contents.
import java.io.Console;
import java.util.Arrays;
public class SetPassword {
static void wipe(char[] chars) {
if (chars != null) {
Arrays.fill(chars, '\0');
}
}
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.err.println("No console available");
return;
}
char[] first = null;
char[] second = null;
try {
first = console.readPassword("%s", "New password: ");
second = console.readPassword("%s", "Repeat password: ");
if (first == null || second == null) {
System.err.println("Input ended before both passwords were read.");
} else if (first.length < 8) {
System.err.println("Use at least 8 characters.");
} else if (!Arrays.equals(first, second)) {
System.err.println("The passwords do not match.");
} else {
System.out.println("Password accepted (" + first.length + " characters).");
}
} finally {
wipe(first);
wipe(second);
}
}
}The program prints only the length of the password, never the password itself. The finally block runs even if an exception interrupts the code between the reads and the comparison.
A real application would not compare two raw passwords this way to authenticate someone. It would hash the characters with a slow password-hashing function (for example PBKDF2 through SecretKeyFactory) and compare hashes. The array handling shown above still applies.
Return values and errors
readLineandreadPasswordreturnnullwhen the end of the input is reached. This is the same signal thatScanner.hasNextLine()reports asfalse.- An empty line gives an empty
Stringor a zero-lengthchar[], notnull. - If a read fails at the operating system level, the methods throw
java.io.IOError. It is anError, not a checkedIOException, so you are not forced to catch it. Most programs let it end the run. readLinestrips the line terminator. TheScannernewline pitfall does not occur, becauseConsolehas no token-reading methods.
Mixing Console with other readers
Console has its own buffering. If you wrap System.in in a Scanner or BufferedReader and also call console.readLine() in the same program, the two readers compete for the same stream. Either reader may have already pulled bytes into its buffer, and the other reader never sees them. Choose one source of input for the whole program.
If you want number parsing with a hidden password, read everything through Console and convert the strings yourself:
import java.io.Console;
public class AgeFromConsole {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.err.println("No console available");
return;
}
String text = console.readLine("Age: ");
if (text == null) {
System.err.println("Input ended");
return;
}
try {
int age = Integer.parseInt(text.trim());
console.printf("Next year you will be %d.%n", age + 1);
} catch (NumberFormatException e) {
console.printf("Not a number: %s%n", text);
}
}
}Console.printf writes to the terminal and, like readLine, uses format strings, so %n and %d work as they do in System.out.printf.
Common mistakes
- Calling
console.readLine()without a null check onconsole, which gives aNullPointerExceptionin an IDE or a pipe. - Passing user-controlled text as the format string of a prompt.
- Converting the password to a
String"just for comparing". Compare withArrays.equalsor hash the characters. - Wiping the array only on the success path. Use
finally. - Calling
Arrays.fillon anullresult after the user ended the input. - Testing the program by redirecting a file into it and expecting hidden-input behavior. With redirected input there is no terminal to switch echo off on.
When to choose Console
Choose Console when the program is a command-line tool that a person runs in a terminal and it must read a secret. For input that may come from files or pipes, Scanner or BufferedReader is the right tool, because they work on any InputStream. The last chapter compares all options side by side.
Exercise
A program calls console.readPassword("Password: ") and then immediately Arrays.fill(password, ' '). It crashes with a NullPointerException when the user presses Ctrl+D at the prompt. Why, and how do you fix it?
Show answer
At the end of the input, readPassword returns null, not an empty array. Passing null to Arrays.fill throws the exception. Check password != null before using or wiping it, for example with a helper wipe(char[] chars) that does nothing for null, and call it from a finally block.
Exercise
Why does console.readLine("Progress: 50%") fail, and what is the safest way to print an arbitrary prompt?
Show answer
The prompt is a format string, and a lone % starts a format specifier that is incomplete, so the call throws an IllegalFormatException subclass. Write %% for a literal percent sign, or pass the text as an argument: console.readLine("%s", prompt).
Exercise
Your program works in a terminal but prints "No console available" when run from your IDE. Name two other ways to trigger the same message on older JDKs, and one extra check available from Java 22.
Show answer
Redirecting input from a file (java Login < file.txt) and piping input into the program (echo x | java Login) also make System.console() return null on older JDKs. From Java 22 you can also call console.isTerminal() to check that a person is at a terminal, because System.console() may return a non-null Console even when the streams are redirected.