Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Console input and output with streams

Console input and output with streams in Java: how byte and character streams work, common classes (System.in/out/err, InputStreamReader, BufferedReader, Scanner, PrintWriter), sample programs, and exam-focused notes.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Reading from and writing to the console is a basic I/O skill that every Java engineer uses for small tools, debugging, and university programming problems. Understanding streams (byte and character streams), buffering, and the common classes lets you write robust command-line programs and handle input/output efficiently.

Key ideas

  • Reader and Writer: abstract base classes for character streams. Use these when you want to process text with characters and encodings, instead of raw bytes.

  • InputStreamReader: adapts an InputStream (bytes) into a Reader (characters) using a character encoding (default platform encoding or specified one). Always remember that console bytes are interpreted by some encoding; so using InputStreamReader makes your program handle characters correctly. Since Java 18, Charset.defaultCharset() is UTF-8 by default (unless overridden); for portability, prefer specifying StandardCharsets.UTF_8 explicitly.

  • BufferedReader: wraps a Reader and buffers input for efficiency. It also provides readLine() which returns a full line of text (without the line-terminator) and returns null at end-of-stream (EOF). BufferedReader.readLine() throws IOException.

  • Scanner: a high-level utility that can parse tokens (ints, doubles, words) from an InputStream or Readable. It uses regular expressions to split input into tokens. Scanner.nextInt() reads an integer token; it does not consume the newline after the integer if you call nextLine() afterwards — you must call an extra nextLine() to move past the end of line.

  • PrintStream and PrintWriter: convenience classes for formatted textual output. System.out is a PrintStream. Use printf or format for formatted output. These classes suppress IOExceptions during writes; use checkError() to detect write errors.

  • Flushing and closing: many output streams buffer data. flush() forces buffered bytes to be written out. close() closes the stream and flushes remaining data. Avoid closing System.in/System.out/System.err or wrappers created around them (e.g., Scanner or BufferedReader on System.in), and avoid try-with-resources for those standard streams; closing them prevents further I/O in the process. System.out is a PrintStream that auto-flushes on println and when printf/format write a newline; call flush() explicitly if you need output to appear before a newline.

  • try-with-resources: recommended for automatic closing of streams that implement AutoCloseable (most Readers/Writers, Scanner, etc.). Do not rely on finalizers for resource cleanup.

  • Console: System.console() returns a Console object when run from a real terminal. It may return null in many IDEs or when input/output are redirected; check for null before use.

  • Redirection and pipes: on the command line you can redirect input ("< file") or output ("> file") and use pipes ("|") between programs. Java programs read from System.in and write to System.out so they work with shell redirection naturally.

  • Exceptions: IOException is common with Readers/Writers. Scanner throws InputMismatchException for wrong token type and NoSuchElementException at EOF when input is missing.

Diagram to draw for an exam question: draw three boxes labelled "Byte stream (InputStream)" -> arrow -> "InputStreamReader (decoding)" -> arrow -> "BufferedReader (readLine)". Label where encoding occurs and where buffering occurs.

Formulas (syntax to remember)

InputStream in = System.in; - in is a byte stream for standard input.

BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); - wrap bytes to chars and add buffering. BufferedReader br = new BufferedReader(new InputStreamReader(System.in, java.nio.charset.StandardCharsets.UTF_8)); - specify UTF-8 explicitly (recommended for portability).

String s = br.readLine(); - read a line, may throw IOException.

Scanner sc = new Scanner(System.in); - token-based input, convenient parsing methods. Scanner sc = new Scanner(System.in, java.nio.charset.StandardCharsets.UTF_8.name()); - specify input charset explicitly.

int n = sc.nextInt(); - read an integer token, throws InputMismatchException on bad token.

sc.nextLine(); - consume rest of current line (use after nextInt when mixing with nextLine).

System.out.println("text"); - print text with newline.

System.out.print("prompt: "); - print without newline (useful for input prompts).

System.out.printf("%d %s%n", n, s); - formatted output; use %n for platform-independent newline.

try (BufferedReader br = ...) { ... } - automatic resource closing.

int b = System.in.read(); - read one byte (0..255) or -1 for EOF; throws IOException.

System.out.write(byteArray); - write raw bytes.

Console console = System.console(); - may be null; use console.readLine("prompt: ") to read a line; use console.readPassword("Password: ") for password input without echo.

Worked examples

Example 1 — Scanner with an integer and a line (complete program)

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter number: ");
    int n = sc.nextInt();
    sc.nextLine(); // consume end-of-line
    System.out.print("Enter name: ");
    String name = sc.nextLine();
    System.out.println("Number: " + n);
    System.out.println("Name: " + name);
    // do not close Scanner wrapping System.in in small programs
  }
}

Sample input (user types):

42 Rama

Program output (excluding lines typed by the user; consoles typically echo user input on the same line as the prompt):

Enter number: Enter name: Number: 42 Name: Rama

(Note: prompts appear before user input; consoles usually show the typed input on same lines.)

Example 2 — BufferedReader reading two integers and printing sum (handles lines)

import java.io.*;
class SumTwo {
  public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Enter first integer: ");
    String s1 = br.readLine();
    System.out.print("Enter second integer: ");
    String s2 = br.readLine();
    int a = Integer.parseInt(s1.trim());
    int b = Integer.parseInt(s2.trim());
    System.out.println("Sum = " + (a + b));
    // Do not close br here; it would close System.in
  }
}

Sample interactive input:

10 20

Program output (excluding lines typed by the user):

Enter first integer: Enter second integer: Sum = 30

Example 3 — Byte copy program (acts like Unix cat):

import java.io.*;
class CopyBytes {
  public static void main(String[] args) throws IOException {
    int b;
    while ((b = System.in.read()) != -1) {
      System.out.write(b);
    }
    System.out.flush();
  }
}

If input is "Hello\n" the exact output will be "Hello\n" (same bytes copied). This example shows raw byte I/O; useful for binary data.

Common mistakes

  • Closing System.in or System.out unexpectedly and then trying to use them again.
  • Using byte streams for text without considering encoding (e.g., treating bytes as chars directly) — causes wrong characters for non-ASCII input.
  • Not flushing buffered output when program waits or when piping output — data can remain in buffers.
  • Ignoring checked exceptions for Readers/Writers; forgetting to handle or declare IOException.
  • Reading with BufferedReader.read() and casting to char without checking for -1 (EOF).
  • Using Scanner for very large input in performance-critical code; Scanner is convenient but slower than buffered readers and manual parsing.

For your exam

Question types you will see:

  • Definitions: "What is an InputStream?" or "Define Reader and Writer". A full answer includes the class hierarchy, byte vs char distinction, and examples.
  • Short notes: explain BufferedReader, Scanner, PrintWriter, or System.console() and where to use them.
  • Program writing: small Java programs that read input and produce output (e.g., read n numbers and print sum; parse words; read lines). Include imports, class, main method, exception handling or throws clause, and sample input/output.
  • Debugging: identify why a program using Scanner.nextInt() then nextLine() fails (answer: newline remains; fix by extra nextLine()).
  • Diagrams: show how bytes flow from System.in through InputStreamReader to BufferedReader and where buffering/decoding occur.

What a full-marks program answer includes:

  • Correct imports and class declaration.
  • Proper use of streams with resource cleanup (try-with-resources or explicit close).
  • Correct parsing and exception handling (throws IOException or try-catch as required).
  • Exact sample input and exact output for the sample run.

Quick check

  1. Which class would you use to read a whole line of text conveniently from the console?
  2. What method do you call on a PrintStream or PrintWriter to print formatted output?
  3. Why might System.console() return null?

Answers: 1. BufferedReader (with InputStreamReader) — use BufferedReader.readLine(). 2. printf (or format). 3. Because the program runs inside an IDE or with redirected input/output, not a real terminal; System.console() returns null in those environments.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?