Java Console Input
The Console Class
java.io.Console represents the interactive text terminal a program was started from — the window where a user types commands. You get it with System.console():
Console console = System.console();
Scanner and BufferedReader read from System.in, which may be a keyboard, a pipe or a file. Console is specifically for talking to a person at a terminal, and it offers one thing the others can't: reading a password without displaying it on the screen.
| Method | Purpose |
|---|---|
readLine() / readLine(format, args...) | Optionally print a formatted prompt, then read one line of text. Returns null at end of input |
readPassword() / readPassword(format, args...) | Same, but echoing is turned off while the user types, and the result is a char[] |
printf(format, args...) / format(...) | Write formatted text to the terminal |
reader() / writer() | A Reader / PrintWriter connected to the console, for code that needs stream objects |
flush() | Flush pending output |
charset() (Java 17+) | The charset the console uses |
Use Console for command-line tools that ask a person for credentials or confirmation: database setup scripts, admin-account creation, key-store passwords, git-style login prompts.
When System.console() Returns null
A console exists only when the JVM is connected to an interactive terminal. On Java 21 (and again from Java 25), System.console() returns null when:
- standard input or output is redirected or piped (
java Tool < input.txt,echo x | java Tool,java Tool > out.txt), - the program runs in most IDE run windows,
- it runs as a background service, in a cron job, or in a container without
-it.
Code must therefore always check for null and react sensibly — usually by explaining that the tool needs a terminal, or by falling back to another input source.
Java 22 to 24 behave differently: in those versions the default console implementation (based on the JLine library) returns a Console object even when the streams are redirected. Java 22 also added Console.isTerminal(), which reports whether the console is really attached to a terminal. Java 25 switched the default implementation back, so null is again returned for redirected streams. Code that must behave the same on every version checks both:
Console console = System.console();
boolean interactive = console != null /* Java 22+: && console.isTerminal() */;
(The isTerminal() call only compiles on Java 22 or newer.)
Reading Text and Passwords
import java.io.Console;
public class C1 {
public static void main(String[] args) {
Console console = System.console();
if (console == null) {
System.err.println("No interactive console. Run this program from a terminal.");
System.exit(1);
}
String user = console.readLine("Username: ");
char[] password = console.readPassword("Password for %s: ", user);
try {
console.printf("Read %d password characters for %s%n", password.length, user);
} finally {
java.util.Arrays.fill(password, '\0');
}
}
}
Run in a terminal, where the user types asha and then the password s3cret!pw:
Username: asha
Password for asha:
Read 9 password characters for asha
Run with piped input on Java 21 (echo x | java C1):
No interactive console. Run this program from a terminal.
How it works:
readLine("Username: ")prints the prompt and reads the line the user types. The typed text is visible, as with any normal input.readPassword("Password for %s: ", user)prints a formatted prompt (the same format syntax asprintf), then disables echoing, so nothing appears on the screen as the user types — not even asterisks. Echoing is restored when the user presses Enter.- The password comes back as a
char[], not aString. Strings are immutable: once a password is in aString, it stays in memory until the garbage collector happens to reclaim it, and it may end up in heap dumps or logs. An array can be overwritten as soon as it's no longer needed, which thefinallyblock does withArrays.fill(password, '\0'). This is why security-related Java APIs (KeyStore,PBEKeySpec, JDBC'sDataSourceimplementations) acceptchar[]passwords. - Without a console, the program writes the message to
System.errand exits with code 1, so scripts can detect the failure.
Both read methods return null when the input ends (Ctrl+D on Linux and macOS, Ctrl+Z then Enter on Windows). Production code must handle that instead of calling methods on the null result.
Console Compared with Scanner and System.in
Console | Scanner(System.in) / BufferedReader | |
|---|---|---|
| Works with pipes and redirected files | No (null on Java 21 and 25+; on Java 22–24, isTerminal() is false) | Yes |
| Hidden password input | Yes — readPassword | No — the password is displayed as it's typed |
| Prompt and read in one call | Yes — readLine(prompt) | No — print then nextLine |
| Parses numbers and tokens | No — only whole lines | Scanner: yes |
| Works in IDE run consoles | Usually not | Yes |
| Typical use | Interactive admin and setup tools, credentials | General input, scripts, piped data |
A common design for tools that must work both interactively and in automation: use Console when it's available, and otherwise read values from arguments, environment variables or files — never by prompting through a pipe for a password, and never by putting passwords on the command line, where other users can see them in the process list.
Practical Example: Creating an Administrator Account
Applications often ship a small command-line tool that creates the first administrator account. It must validate input, ask for the password twice without displaying it, enforce a minimum strength, store only a hash of the password — never the password itself — and clear the password from memory afterwards.
import java.io.Console;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import java.util.*;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class CreateAdmin {
static String validateUsername(String name) {
if (name == null || !name.matches("[a-z][a-z0-9_]{2,19}")) {
return "3-20 characters: lowercase letters, digits, underscore; must start with a letter";
}
return null;
}
static String validatePassword(char[] pw) {
if (pw.length < 10) return "at least 10 characters";
boolean letter = false, digit = false;
for (char c : pw) {
if (Character.isLetter(c)) letter = true;
if (Character.isDigit(c)) digit = true;
}
return letter && digit ? null : "must contain letters and digits";
}
static String hash(char[] password) throws Exception {
byte[] salt = new byte[16];
new SecureRandom().nextBytes(salt);
KeySpec spec = new PBEKeySpec(password, salt, 210_000, 256);
byte[] key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
return "pbkdf2$210000$" + Base64.getEncoder().encodeToString(salt) + "$" + Base64.getEncoder().encodeToString(key);
}
public static void main(String[] args) throws Exception {
Console console = System.console();
if (console == null) {
System.err.println("create-admin must be run interactively from a terminal.");
System.exit(1);
}
String user;
while (true) {
user = console.readLine("Admin username: ");
if (user == null) return; // Ctrl+D / end of input
user = user.strip();
String problem = validateUsername(user);
if (problem == null) break;
console.printf(" invalid username: %s%n", problem);
}
char[] pw = null, again = null;
try {
while (true) {
pw = console.readPassword("Password: ");
again = console.readPassword("Repeat password: ");
if (pw == null || again == null) return;
String problem = validatePassword(pw);
if (problem != null) {
console.printf(" weak password: %s%n", problem);
} else if (!Arrays.equals(pw, again)) {
console.printf(" passwords do not match%n");
} else {
break;
}
Arrays.fill(pw, '\0');
Arrays.fill(again, '\0');
}
String stored = hash(pw);
console.printf("Created admin '%s'. Stored hash starts with %s...%n", user, stored.substring(0, 14));
} finally {
if (pw != null) Arrays.fill(pw, '\0');
if (again != null) Arrays.fill(again, '\0');
}
}
}
A terminal session in which the user first enters an invalid username, then a too-short password, then two different passwords, and finally two matching ones (passwords are never shown):
Admin username: Asha
invalid username: 3-20 characters: lowercase letters, digits, underscore; must start with a letter
Admin username: asha_rao
Password:
Repeat password:
weak password: at least 10 characters
Password:
Repeat password:
passwords do not match
Password:
Repeat password:
Created admin 'asha_rao'. Stored hash starts with pbkdf2$210000$...
Step by step:
- Refusing to run without a terminal. A pipe can't provide hidden password input, so the tool stops with a clear message and a non-zero exit code rather than reading a password from somewhere insecure.
- Username validation uses a regular expression: a lowercase letter followed by 2–19 lowercase letters, digits or underscores.
Ashafails because of the capital letter; the loop asks again. Anullresult (end of input) ends the program quietly. - Password entry twice. Both entries are read with
readPassword, checked for strength (at least 10 characters, with letters and digits) and compared withArrays.equals. Any failure clears both arrays and repeats the prompts. - Hashing. Passwords must be stored as a slow, salted hash so that a stolen database doesn't reveal them.
PBKDF2WithHmacSHA256is built into the JDK: a random 16-byte salt makes identical passwords produce different hashes, and 210,000 iterations make guessing expensive. The stored string records the algorithm, iteration count, salt and hash, so the password can be verified later by repeating the calculation. (Dedicated libraries for bcrypt, scrypt or Argon2 are common alternatives.) - Clearing secrets. The
finallyblock overwrites both arrays even if hashing throws.PBEKeySpeccopies the password internally, and callingspec.clearPassword()would clear that copy too in hardened code. - Only a short prefix of the hash is printed, which confirms the format without showing the full value.
Prompts and messages go through console.printf, so they appear on the terminal even if the tool's normal output were redirected elsewhere.