Java Console Class

Beginner
8 min read
Updated: Nov 2026
3 examples
java.io.Console

Definition and Usage

In Java, java.io.Console (since Java 6) gives your program character-based access to the interactive terminal it was started from: the keyboard for input and the screen for output. You cannot create one with new. The JVM has at most one console, and System.console() hands it to you.

Its methods fall into two groups. Input: readLine() reads a line, readPassword() reads a secret without showing it, and reader() returns a Reader. Output: format() and printf() print formatted text, writer() returns a PrintWriter, and flush() pushes buffered text out. Java 17 added charset(). The Console Methods index lists every guide.

System.console() can return null.

When the program is not attached to an interactive terminal, for example in many IDE run windows or with redirected input, there is no console and System.console() returns null. Calling a method on it then throws NullPointerException, so every program must check first.

Java Syntax

Import the class, get the console, and handle the null case before anything else:

Java
import java.io.Console;

Console console = System.console();
if (console == null) {
    System.out.println("No console available. Run this from a terminal.");
    return;
}
String name = console.readLine("Name: ");        // visible input
char[] secret = console.readPassword("PIN: ");   // hidden input
console.printf("Hello, %s!%n", name);            // formatted output

When Is System.console() null?

Whether a console exists depends on how the program was started, not on your code:

How the program runsSystem.console() (Java 8 to 21)
java App in Command Prompt, PowerShell, or a macOS/Linux terminalA Console object
The run window of many IDEsUsually null
Input redirected or piped: java App < in.txt, echo hi | java Appnull
Output redirected: java App > out.txtnull
Started by a build tool task (Gradle, Maven), a scheduler, or as a background serviceUsually null

Newer JDKs changed this a little: starting with Java 22, some versions can return a Console even when input or output is redirected, and the new Console.isTerminal() method tells you whether it is really attached to a terminal. Because the behaviour depends on the Java version, keep the null check in every program.

Console vs Scanner vs System.in and System.out

Three common ways to talk to the user, and what each is good at:

FeatureConsoleScanner + System.in / System.out
How you get itSystem.console() (may be null)new Scanner(System.in); System.out always exists
Works in IDEs, pipes, and filesOften notYes
Hidden password inputYes, readPassword()No; typed text is always visible
Prompt and read in one callreadLine("Name: ")Print, then nextLine()
Parse numbers and wordsWrap reader() in a ScannernextInt(), nextDouble(), next()
Formatted outputprintf(), flushed every callSystem.out.printf()
End of inputreadLine() returns nullnextLine() throws NoSuchElementException

Reading Passwords Safely

readPassword() is the main reason to choose Console. It turns off echoing, so nothing appears while the user types, and it returns a char[] instead of a String. Check the characters, then overwrite them with Arrays.fill(password, ' ') so the secret does not stay in memory longer than needed.

Never print or log a password, never turn it into a String just to compare it, and never hard-code a real password in source code. Real programs compare a salted hash stored elsewhere.

Java Examples

Example 1 — Use the Console When There Is One, Fall Back When There Is Not

Ask for a name through the console in a terminal. When System.console() is null, read the same answer from System.in instead of crashing.

Java
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;

public class ConsoleHubFallback {
    public static void main(String[] args) throws IOException {
        Console console = System.console();
        String name;
        if (console != null) {
            name = console.readLine("Name: ");
        } else {
            System.out.println("No console available - reading from System.in instead.");
            System.out.println("Enter your name:");
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            name = in.readLine();
        }
        System.out.println("Hi, " + (name == null ? "stranger" : name.trim()) + "!");
    }
}

How It Works

  1. Ask once, decide once. System.console() is called a single time and the result is stored, because the answer will not change while the program runs.
  2. Terminal branch. With a real terminal, readLine("Name: ") prints the prompt and returns the typed name, here Alice.
  3. Fallback branch. With input redirected from a file, there is no console, so the program wraps System.in in a BufferedReader and reads the first line, Bob. The typed text is not echoed because nobody typed it.
  4. One shared ending. Both branches leave a String (or null at end of input) in name, so the greeting code works for either source.

Example 2 — A Tiny Sign-Up Form with Hidden Password Input

Read a visible username and a hidden password, then report only the password length and wipe the characters.

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

public class ConsoleHubSignUp {
    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;
        }
        String user = console.readLine("Choose a username: ");
        if (user == null) {
            return;
        }
        char[] pass = console.readPassword("Choose a password: ");
        if (pass == null) {
            return;
        }
        int length = pass.length;
        Arrays.fill(pass, ' ');
        console.printf("Account '%s' created (password: %d characters, not shown).%n", user, length);
    }
}

How It Works

  1. Visible field. The username is not secret, so plain readLine is used and the letters appear as they are typed.
  2. Hidden field. readPassword switches echo off, so the terminal shows nothing while the nine characters are typed, then moves to the next line.
  3. Keep only what you need. The program saves the length in an int and immediately overwrites the char[] with spaces using Arrays.fill.
  4. Safe summary. The final printf reports the username and the length, never the password itself.

Example 3 — Read Two Scores and Print a Formatted Average

Text from readLine is always a String; convert it with Integer.parseInt, then print a rounded average with printf.

Java
import java.io.Console;

public class ConsoleHubAverage {
    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;
        }
        String a = console.readLine("First test score: ");
        String b = console.readLine("Second test score: ");
        if (a == null || b == null) {
            console.printf("Input ended early.%n");
            return;
        }
        int first = Integer.parseInt(a.trim());
        int second = Integer.parseInt(b.trim());
        console.printf("Average: %.2f%n", (first + second) / 2.0);
        console.printf("Best: %d%n", Math.max(first, second));
    }
}

How It Works

  1. Two prompts. Each readLine call prints its prompt and waits for Enter, giving the strings "78" and "91".
  2. Text to numbers. trim() removes stray spaces and Integer.parseInt turns each string into an int; letters here would throw NumberFormatException.
  3. Decimal division. Dividing by 2.0 instead of 2 keeps the fraction, so (78 + 91) / 2.0 is 84.5, and %.2f prints it as 84.50.
  4. Larger value. Math.max picks 91, printed with %d.

Next: Java Console Methods by Group

GroupMethods
Write output to the terminalformat(), printf(), writer(), flush()
Read input from the keyboardreadLine(), readPassword(), reader()
Console informationcharset()

Full list with short descriptions: Java Console Methods index.

Frequently Asked Questions

A class, available since Java 6, that gives character-based access to the interactive terminal a program was started from: reading lines and passwords from the keyboard and writing formatted text to the screen.
No interactive console is attached, for example in many IDE run windows, when input or output is redirected or piped, or when the program runs under a build tool or as a background service. Always check for null before using it.
Use Scanner with System.in for general input that must also work with files, pipes, and IDEs. Use Console when you need hidden password input or want to require a real terminal.
Call System.console().readPassword("Password: "). It turns echo off and returns a char[], which you should overwrite with Arrays.fill once you have checked it.
Not exactly. Up to Java 21 it returns null whenever input or output is redirected. Starting with Java 22, some JDK versions can return a Console in more situations, and Console.isTerminal() was added to check for a real terminal. Keep the null check and test on the Java version you use.

Browse every Console method

Open the methods index for categorized guides with terminal examples and FAQs.

Console Methods Index →

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.

9 people found this page helpful