Java Console Input

Su Suriya Ravichandran Updated 18 Nov 2026
8 min read ·Lesson 151 of 306

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.

MethodPurpose
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:

  1. readLine("Username: ") prints the prompt and reads the line the user types. The typed text is visible, as with any normal input.
  2. readPassword("Password for %s: ", user) prints a formatted prompt (the same format syntax as printf), then disables echoing, so nothing appears on the screen as the user types — not even asterisks. Echoing is restored when the user presses Enter.
  3. The password comes back as a char[], not a String. Strings are immutable: once a password is in a String, 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 the finally block does with Arrays.fill(password, '\0'). This is why security-related Java APIs (KeyStore, PBEKeySpec, JDBC's DataSource implementations) accept char[] passwords.
  4. Without a console, the program writes the message to System.err and 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

ConsoleScanner(System.in) / BufferedReader
Works with pipes and redirected filesNo (null on Java 21 and 25+; on Java 22–24, isTerminal() is false)Yes
Hidden password inputYes — readPasswordNo — the password is displayed as it's typed
Prompt and read in one callYes — readLine(prompt)No — print then nextLine
Parses numbers and tokensNo — only whole linesScanner: yes
Works in IDE run consolesUsually notYes
Typical useInteractive admin and setup tools, credentialsGeneral 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:

  1. 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.
  2. Username validation uses a regular expression: a lowercase letter followed by 2–19 lowercase letters, digits or underscores. Asha fails because of the capital letter; the loop asks again. A null result (end of input) ends the program quietly.
  3. Password entry twice. Both entries are read with readPassword, checked for strength (at least 10 characters, with letters and digits) and compared with Arrays.equals. Any failure clears both arrays and repeats the prompts.
  4. Hashing. Passwords must be stored as a slow, salted hash so that a stolen database doesn't reveal them. PBKDF2WithHmacSHA256 is 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.)
  5. Clearing secrets. The finally block overwrites both arrays even if hashing throws. PBEKeySpec copies the password internally, and calling spec.clearPassword() would clear that copy too in hardened code.
  6. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Console Input and get answers drawn from it.

Signed-in readers only.