Java Console and User Interaction: System.in, System.out, System.err and Console (OCP 21)
User interaction for the OCP 21 exam: System.out versus System.err, reading System.in through BufferedReader, why closing system streams breaks output silently, java.io.Console with readLine, readPassword, writer and format, and the newer isTerminal and java.lang.IO.
kvi5hnuCode Sprout team member8 min readOn this page
Every stream in the last few articles was one you opened, so you closed it with try-with-resources. This article covers three streams the JVM opens for you, System.in, System.out and System.err, plus java.io.Console, a helper built for interactive programs. The exam tests the types involved, the null check for Console, readPassword's return type, and what happens when someone closes a system stream.
Printing: System.out and System.err
System.out and System.err are both PrintStream objects (public static final fields of System). They have the same methods: print, println, printf and format. They differ only in where the text goes:
System.outis standard output, for normal results.System.erris standard error, a separate channel for problems.
try (var in = Files.newBufferedReader(Path.of("seats.csv"))) {
System.out.println("Seat map loaded");
} catch (NoSuchFileException e) {
System.err.println("Seat map not found, using defaults");
}
In a terminal both usually show up in the same window. An IDE often prints the error stream in red. A shell can redirect them separately (java App > out.log 2> err.log), and servers usually send them to different log files. Because they're separate channels, their lines can come out in a surprising order when you see them together.
Formatting
PrintStream and PrintWriter both offer format(String, Object...) and format(Locale, String, Object...). printf is just another name for format, with the same parameters and behaviour. Both return the stream itself, so calls can be chained:
System.out.printf(Locale.ROOT, "%-8s|%5.1f|%04d%n", "garden", 128.91, 42)
.format(Locale.ROOT, "%,d visitors%n", 1250000);
// garden |128.9|0042
// 1,250,000 visitors
Use %n rather than \n for the platform line separator. If you leave out the Locale, the default locale decides details like the decimal separator.
Reading: System.in
System.in is a plain InputStream of bytes. To read whole lines of text, wrap it in two layers: a bridge that turns bytes into characters, then a buffer that adds readLine():
var reader = new BufferedReader(new InputStreamReader(System.in));
String answer = reader.readLine(); // waits until the user presses Enter
System.out.println("You typed: " + answer);
readLine() returns the line without its line break. It returns null when the input ends, for example when the user presses Ctrl+D on Unix or Ctrl+Z on Windows, or when piped input runs out. java.util.Scanner (new Scanner(System.in).nextLine()) is another common choice. The exam focuses on the BufferedReader/InputStreamReader pair.

Don't close the system streams
The JVM creates the three system streams once and shares them across the whole program, so you don't put them in try-with-resources. You can close them (they're ordinary streams), but once closed they stay closed for every thread for the rest of the program.
try (var out = System.out) { } // closes System.out
System.out.println("Hello"); // prints nothing, and no exception
PrintStream methods never throw IOException. They record the failure internally, and you can see it only by calling checkError(), which returns true. Closing System.err is even worse, because the stack traces of uncaught exceptions are printed there and would disappear too.
Input streams aren't so forgiving:
var reader = new BufferedReader(new InputStreamReader(System.in));
try (reader) { } // closes the reader AND System.in under it
reader.readLine(); // IOException: Stream closed
Watch for this pattern: putting a wrapper around System.in in try-with-resources closes System.in itself, because closing a wrapper closes the stream it wraps.
java.io.Console
System.in and System.out are raw streams. Console is a class built for talking to a person at a terminal. Its rules:
- You get it from the factory method
System.console().Consolehas no public constructor, sonew Console()doesn't compile. The JVM gives out at most one instance. System.console()returnsnullwhen no interactive terminal is attached. That's common in IDEs, under build tools, when input or output is redirected, or in a background service. Always check fornullbefore using it.
Console console = System.console();
if (console == null) {
System.err.println("No console available");
return;
}
String name = console.readLine("Name: ");
console.writer().println("Hi " + name);
char[] pin = console.readPassword("PIN (%d digits): ", 4);
// ... use the PIN ...
java.util.Arrays.fill(pin, ' '); // wipe it when done
console.flush();
| Method | Returns | Notes |
|---|---|---|
readLine() / readLine(String fmt, Object... args) | String | The second version prints a formatted prompt first. Returns null at the end of input. |
readPassword() / readPassword(String fmt, Object... args) | char[] | Input isn't echoed (shown) as it's typed. The result isn't encrypted. |
writer() | PrintWriter | Character output to the console. |
reader() | Reader | Character input from the console. |
format(...) / printf(...) | Console | Same as each other, and they can be chained. |
flush() | void | Pushes buffered output to the screen. |
charset() (Java 17) | Charset | The console's character encoding. |
Why does readPassword return char[] and not String? Strings are immutable and may stay in memory (or in the string pool) long after you're done with them. You can overwrite an array as soon as you've checked the password, so it stays in memory for less time. It's a small hardening step, not encryption.
Console's reader() and writer() are character streams, while System.in and System.out are byte streams. That makes the console versions a better fit for text.
What's current
- Java 22 made the JLine-based console the default, so for a while
System.console()returned aConsoleeven without a terminal. It also addedConsole.isTerminal()to tell the two cases apart. Java 25 went back to the original behaviour:System.console()again returnsnullwhen there's no terminal. On Java 21, the exam's version, it returnsnullwhen there's no terminal, so thenullcheck is always right. - Java 23 added
Localeoverloads toConsole:readLine(Locale, ...),readPassword(Locale, ...),format(Locale, ...)andprintf(Locale, ...). On Java 21 onlyPrintStream/PrintWriterhave theLocaleversions, soconsole.format(Locale.ROOT, ...)doesn't compile with--release 21. - Java 25 finalized
java.lang.IO(JEP 512), part of the "compact source files and instance main methods" feature:IO.println(x),IO.print(x),IO.readln()andIO.readln(prompt). It's built onSystem.outandSystem.inand needs no import. It's not on the Java 21 exam. - Since Java 18 the default charset is UTF-8 (JEP 400), but
System.outandSystem.errstill use the terminal's encoding, which is exposed as thestdout.encodingandstderr.encodingproperties (Java 19).
Exam traps from this article
A complete example
The program below shows all of these behaviours with fixed, repeatable output. It captures System.out and System.err in buffers to show they're separate, formats with chained printf/format, and replaces System.in with a short script so the input part needs no typing. The reading code goes through a small Prompt interface with two versions, one for a real Console and one for the System.in fallback, which is the usual way to handle a null console. Finally it closes System.out and System.in on purpose, after swapping in stand-ins so the real streams survive.
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Locale;
public class Solution {
/** One way to talk to the user, so the program works with or without a Console. */
interface Prompt {
String readLine(String fmt, Object... args) throws IOException;
char[] readPassword(String fmt, Object... args) throws IOException;
PrintWriter writer();
}
/** Real terminal: prompts are shown and passwords aren't echoed. */
record ConsolePrompt(Console console) implements Prompt {
public String readLine(String fmt, Object... args) { return console.readLine(fmt, args); }
public char[] readPassword(String fmt, Object... args) { return console.readPassword(fmt, args); }
public PrintWriter writer() { return console.writer(); }
}
/** Fallback: System.in wrapped in a BufferedReader, prompts go to System.out. */
static final class StreamPrompt implements Prompt {
private final BufferedReader in = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
private final PrintWriter out = new PrintWriter(System.out, true);
public String readLine(String fmt, Object... args) throws IOException {
out.printf(Locale.ROOT, fmt, args);
String line = in.readLine(); // null when the input ends
out.println(line); // echo, because our input is a script, not a person
return line;
}
public char[] readPassword(String fmt, Object... args) throws IOException {
out.printf(Locale.ROOT, fmt, args);
String line = in.readLine();
out.println("*".repeat(line == null ? 0 : line.length()));
return line == null ? null : line.toCharArray();
}
public PrintWriter writer() { return out; }
}
static String visible(String s) { return s.replace("\r", "").replace("\n", "\\n"); }
public static void main(String[] args) throws IOException {
PrintStream realOut = System.out, realErr = System.err;
InputStream realIn = System.in;
System.out.println("== 1. System.out and System.err are separate PrintStreams");
var outBuf = new ByteArrayOutputStream();
var errBuf = new ByteArrayOutputStream();
System.setOut(new PrintStream(outBuf, true, StandardCharsets.UTF_8));
System.setErr(new PrintStream(errBuf, true, StandardCharsets.UTF_8));
System.out.println("Ticket booked");
System.err.println("Seat map not found, using defaults");
System.setOut(realOut);
System.setErr(realErr);
System.out.println(" standard output got: " + visible(outBuf.toString(StandardCharsets.UTF_8)));
System.out.println(" standard error got: " + visible(errBuf.toString(StandardCharsets.UTF_8)));
System.out.println("\n== 2. Formatting with printf/format (they're the same method)");
PrintStream chained = System.out.printf(Locale.ROOT, " %-8s|%5.1f|%04d%n", "garden", 128.91, 42)
.format(Locale.ROOT, " %,d visitors%n", 1250000);
System.out.println(" printf returns the same stream: " + (chained == System.out));
System.out.println("\n== 3. Reading user input (System.in replaced by a script for this demo)");
System.setIn(new ByteArrayInputStream("Mira\nhunter22\nhunter22\n".getBytes(StandardCharsets.UTF_8)));
Console console = System.console();
// A Console reads the terminal, not System.in. We replaced System.in, so take the fallback.
boolean inputReplaced = true;
Prompt prompt = console != null && !inputReplaced ? new ConsolePrompt(console) : new StreamPrompt();
System.out.println(" prompt type: " + prompt.getClass().getSimpleName());
String name = prompt.readLine(" Name: ");
prompt.writer().format(" Hello %s%n", name);
char[] password = prompt.readPassword(" Password (%d-%d chars): ", 6, 12);
char[] again = prompt.readPassword(" Again: ");
prompt.writer().println(" passwords match: " + Arrays.equals(password, again));
Arrays.fill(password, '\0'); // wipe secrets once you're done
Arrays.fill(again, '\0');
prompt.writer().println(" wiped: " + new String(password).chars().allMatch(c -> c == 0));
prompt.writer().println(" next line after the script ends: " + prompt.readLine(" More? "));
System.setIn(realIn);
System.out.println("\n== 4. Closing System.out: later output is silently lost");
var target = new ByteArrayOutputStream();
System.setOut(new PrintStream(target, true, StandardCharsets.UTF_8));
try (var out = System.out) { // closes the shared System.out!
out.println("before close");
}
System.out.println("after close"); // no exception: PrintStream swallows it
boolean failed = System.out.checkError();
System.setOut(realOut);
System.out.println(" what reached the stream: " + visible(target.toString(StandardCharsets.UTF_8)));
System.out.println(" checkError() after the lost println: " + failed);
System.out.println("\n== 5. Closing System.in: readers throw IOException");
System.setIn(new ByteArrayInputStream("unused\n".getBytes(StandardCharsets.UTF_8)));
var reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8));
try (reader) { } // also closes System.in underneath
try {
reader.readLine();
} catch (IOException e) {
System.out.println(" readLine() on a closed reader -> " + e.getClass().getSimpleName()
+ " (" + e.getMessage() + ")");
} finally {
System.setIn(realIn);
}
System.out.println("\n== 6. System.console() may be null");
System.out.println(" safe check written: " + (console == null || console.charset() != null));
}
}
Output:
== 1. System.out and System.err are separate PrintStreams
standard output got: Ticket booked\n
standard error got: Seat map not found, using defaults\n
== 2. Formatting with printf/format (they're the same method)
garden |128.9|0042
1,250,000 visitors
printf returns the same stream: true
== 3. Reading user input (System.in replaced by a script for this demo)
prompt type: StreamPrompt
Name: Mira
Hello Mira
Password (6-12 chars): ********
Again: ********
passwords match: true
wiped: true
More? null
next line after the script ends: null
== 4. Closing System.out: later output is silently lost
what reached the stream: before close\n
checkError() after the lost println: true
== 5. Closing System.in: readers throw IOException
readLine() on a closed reader -> IOException (Stream closed)
== 6. System.console() may be null
safe check written: true
Points to notice:
System.setOut,setErrandsetInreplace the system streams. That's useful in tests, and it's how this program closes "System.out" without losing its own output.- Because the program replaced
System.in, it uses the stream version ofPrompteven if a terminal exists. AConsolereads the terminal directly, notSystem.in. - Once the script runs out,
readLine()returnsnull. It doesn't throw. - The passwords are compared with
Arrays.equals, then wiped withArrays.fill, which you can't do with aString. - After
System.outwas closed,"after close"disappeared without any exception, and onlycheckError()reveals it. - The closed
System.inbehaves differently:readLine()throwsIOException: Stream closed.
Common questions
Why does System.console() return null in my IDE?
Many IDEs run your program with its input and output connected to pipes, not to a real terminal, so there's no console to return. Run the program from a terminal, or write a fallback like the Prompt in the example.
Is System.err unbuffered?
In practice, both system print streams flush on every println. The order in which the two channels show up still isn't guaranteed when they're shown together, so don't depend on how out and err lines are mixed.
Should I use Scanner or BufferedReader for System.in?
BufferedReader is simpler and faster for whole lines. Scanner can parse numbers and tokens directly. For the exam, know the BufferedReader(new InputStreamReader(System.in)) pattern.
Can I get the console's input as a byte stream?
No. Console only offers character streams (reader() and writer()). For bytes, use System.in and System.out.
Summary
System.out(normal output) andSystem.err(errors) arePrintStreams.printfequalsformat, and both haveLocaleoverloads.- Read lines from
System.in(anInputStream) throughBufferedReaderwrapping anInputStreamReader.readLine()returnsnullwhen input ends. - Never close the system streams. A closed
System.outfails silently (checkError()istrue), and a closedSystem.inthrowsIOException. - Get a
ConsolefromSystem.console()(no constructor) and check it fornull.readLinereturnsString,readPasswordreturns an unechoedchar[], andwriter(),reader(),format,printfandflushhandle the rest. - Newer releases added
Console.isTerminal()(22),Localeoverloads (23) andjava.lang.IO(25).
Practice quiz
Test yourself with the console and user interaction quiz: 10 exam-style questions with explanations.
Previous: Java Serialization: Serializable, transient, serialVersionUID and Records (OCP 21)
Next: Java Files Advanced: Attributes, walk, find, lines and mark/reset (OCP 21)
Related reading
- Java Serialization: Serializable, transient, serialVersionUID and Records (OCP 21)
- Java Reading and Writing Files: I/O Streams, Buffered Readers and Files Methods (OCP 21)
- Java I/O Streams: Byte and Character, Input and Output, Low-Level and High-Level (OCP 21)
- Java Files: Copying, Moving, Deleting and Comparing Files (OCP 21)
- Java Path Methods: normalize, resolve, relativize and Files Basics (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.