Java Console readLine() Method

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

Definition

In Java, console.readLine() waits until the user types a line and presses Enter, then returns that text as a String without the line break. The second form, readLine(fmt, args...), first prints a formatted prompt such as "Name: " and then reads.

It returns null when the input ends, which happens when the user presses Ctrl+D on macOS or Linux, or Ctrl+Z then Enter on Windows. Always check for null before using the result.

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.readLine(...).

Java 22+ note.

Up to Java 21, System.console() returns null in most IDE run windows and whenever input or output is redirected. From Java 22, some JDK versions may return a Console there too, and Console.isTerminal() was added to tell the cases apart. Keep the null check either way.

Syntax

Use the no-argument form after printing your own prompt, or let readLine print the prompt:

Java
Console console = System.console();
String a = console.readLine();                         // read only
String b = console.readLine("Name: ");                 // prompt, then read
String c = console.readLine("Item %d of %d: ", 1, 3);  // formatted prompt
CallWhat it does
console.readLine()Reads one line; no prompt is printed.
console.readLine("Age: ")Prints Age: and waits on the same line.
console.readLine("Item %d: ", n)Builds the prompt with format specifiers first.
Integer.parseInt(line.trim())Turns a typed number into an int (after a null check).

Available since Java 6. The prompt overload uses the same format rules and default locale as format(). The returned String never contains the line terminator.

Library declarations
Java
// java.io.Console
public String readLine()
public String readLine(String fmt, Object... args)

Parameters

ParameterDescription
fmt (optional)Prompt format string, such as "Name: " or "Item %d: ".
args (optional)Values for the specifiers in fmt.

Return Value

Return ValueDescription
StringThe line the user typed, without the line break. It is empty if the user just pressed Enter.
nullThe end of input was reached (Ctrl+D, or Ctrl+Z then Enter on Windows).

Compare with Similar Methods

Other ways to read what the user types:

MethodHow it differs
readPassword()Same idea, but typing is hidden and a char[] is returned.
reader()A Reader to wrap in a Scanner or BufferedReader.
Scanner.nextLine()Reads System.in; works even without a console.
BufferedReader.readLine()Also returns null at end of input, but throws the checked IOException.

Java Examples

Example 1 — Ask for a Name and Greet the User

The prompt overload prints the question and reads the answer in one call. The null checks cover a missing console and an ended input.

Java
import java.io.Console;

public class ConsoleReadLineGreet {
    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 name = console.readLine("What is your name? ");
        if (name == null) {
            console.printf("No input (end of stream).%n");
            return;
        }
        String clean = name.trim();
        console.printf("Hello, %s! Your name has %d characters.%n", clean, clean.length());
    }
}

How It Works

  1. Prompt inside the call. readLine("What is your name? ") prints the question, leaves the cursor after it, and waits for Enter.
  2. Two different nulls. The first check handles "no console at all"; the second handles a console whose input ended before a line was typed.
  3. Clean the text. trim() removes spaces the user may have typed around the name, so "Alice" is counted as 5 characters.
  4. Formatted reply. printf fills %s with the name and %d with its length.

Example 2 — Add Up Numbers Until the User Types done

A formatted prompt shows which number is being asked for. Bad input is rejected with a message, and the loop also stops at end of input.

Java
import java.io.Console;

public class ConsoleReadLineSum {
    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;
        }
        int total = 0;
        int count = 0;
        while (true) {
            String line = console.readLine("Number %d (or 'done'): ", count + 1);
            if (line == null || line.trim().equalsIgnoreCase("done")) {
                break;
            }
            try {
                total += Integer.parseInt(line.trim());
                count++;
            } catch (NumberFormatException e) {
                console.printf("  '%s' is not a whole number, try again.%n", line);
            }
        }
        console.printf("You entered %d numbers. Sum = %d%n", count, total);
    }
}

How It Works

  1. Prompt with a counter. readLine("Number %d (or 'done'): ", count + 1) formats the prompt first, so the user sees which number is next.
  2. Two ways out. The loop ends when the user types done (in any letter case) or when readLine returns null because the input ended.
  3. Reject bad input. "abc" makes Integer.parseInt throw NumberFormatException; the catch prints a hint and count is not increased, so the prompt asks for number 2 again.
  4. Result. Only 12 and 30 were accepted, so the summary reports 2 numbers with a sum of 42.

Example 3 — Read Lines Until End of Input

The no-argument readLine() returns null when the user signals end of input, which makes a simple while loop possible.

Java
import java.io.Console;

public class ConsoleReadLineEcho {
    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;
        }
        console.printf("Type lines. Press Ctrl+D (macOS/Linux) or Ctrl+Z then Enter (Windows) to finish.%n");
        int lines = 0;
        String longest = "";
        String line;
        while ((line = console.readLine()) != null) {
            lines++;
            if (line.length() > longest.length()) {
                longest = line;
            }
        }
        console.printf("Read %d lines. Longest: \"%s\" (%d chars)%n", lines, longest, longest.length());
    }
}

How It Works

  1. Instructions first. The program tells the user which keys end the input, because the keys differ between Windows and macOS/Linux.
  2. Assign and test. (line = console.readLine()) != null reads a line and checks it in the same expression, so the loop body only runs for real lines.
  3. Track the longest. "green apple" (11 characters, the space counts) beats "red" and "sky", so it is kept in longest.
  4. End of input. Ctrl+D makes readLine() return null, the loop stops, and the summary escapes the quotes with \" to print them around the text.

Frequently Asked Questions

The line the user typed as a String, without the line break, or null if the end of input was reached.
System.console() returned null because the program is not attached to an interactive terminal, as happens in many IDE run windows or with redirected input. Check for null, and run the program with java ClassName in a terminal.
Pass it as the first argument: console.readLine("Name: "). You can use format specifiers too, as in console.readLine("Item %d: ", 2).
By pressing Ctrl+D on macOS and Linux, or Ctrl+Z followed by Enter on Windows. readLine() then returns null.
Read the text, check that it is not null, then convert it with Integer.parseInt(line.trim()) and catch NumberFormatException for invalid input.

Next: readPassword()

Read a password or PIN without showing the typed characters, returned as a char array.

readPassword() 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.

11 people found this page helpful