00:00

PrintStream Class in Java: print, println and printf

Last updated:

Every Java developer has used PrintStream, often without knowing it: System.out and System.err are PrintStream objects. The same class can print text to files, sockets or memory, with the familiar print(), println() and printf() methods.

This tutorial covers the class, its constructors and methods, its unusual error handling and when to prefer PrintWriter.

1. What Is PrintStream in Java?

PrintStream is a filter output stream that turns values of any type, such as numbers, booleans and objects, into their text form and writes them as bytes, using a charset. It has two special features:

  • It never throws IOException. Errors set an internal flag that you check with checkError().
  • It can flush automatically after println(), after writing a byte array, or when a newline is written.

2. PrintStream Class Hierarchy

PrintStream class hierarchyPrintStream extends FilterOutputStream, which extends OutputStream and Object. It implements Appendable, Closeable, Flushable and AutoCloseable. The familiar System.out and System.err objects are PrintStream instances.ObjectextendsOutputStreamabstract classextendsFilterOutputStreamwraps another OutputStreamextendsPrintStreamprints values as text bytesAppendableCloseableFlushableAutoCloseableimplementsFamiliar instancesSystem.outSystem.err

Swipe sideways to see the whole diagram.

3. Constructors of PrintStream

ConstructorDescription
PrintStream(OutputStream out)Prints to another stream, without automatic flushing.
PrintStream(OutputStream out, boolean autoFlush, Charset charset)Adds automatic flushing and an explicit charset (Java 10).
PrintStream(String fileName) / PrintStream(File file)Prints to a file, replacing its content (Java 5).
PrintStream(File file, Charset charset)Prints to a file with an explicit charset (Java 10).

4. Commonly Used Methods

MethodDescription
print(x) / println(x)Prints any primitive, String, char[] or object; println adds a line separator.
printf(format, args...) / format(...)Formatted output, such as "%.2f" (Java 5).
append(CharSequence csq)Appends text; returns the stream for chaining (Java 5).
checkError()Flushes and returns true if any error has occurred.
writeBytes(byte[] buf)Writes raw bytes (Java 14).
charset()Returns the charset used to encode characters (Java 18).

5. Example: Printing an Invoice to a File

An electronics shop prints invoices to text files. printf() aligns the columns, and an explicit charset makes the file predictable.

InvoicePrinter.java
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Locale;

public class InvoicePrinter {
    public static void main(String[] args) throws IOException {
        Path invoice = Files.createTempFile("invoice", ".txt");
        String[] items = {"Keyboard", "Mouse", "USB-C cable"};
        double[] prices = {1899.0, 649.5, 299.0};

        try (PrintStream out = new PrintStream(invoice.toFile(), StandardCharsets.UTF_8)) {   // Java 10
            out.println("INVOICE #2026-118");
            double total = 0;
            for (int i = 0; i < items.length; i++) {
                out.printf(Locale.ROOT, "%-12s %9.2f%n", items[i], prices[i]);
                total += prices[i];
            }
            out.printf(Locale.ROOT, "%-12s %9.2f%n", "TOTAL", total);
            System.out.println("Charset used: " + out.charset());                            // Java 18
        }
        System.out.print(Files.readString(invoice));
        Files.delete(invoice);
    }
}
Output
Charset used: UTF-8
INVOICE #2026-118
Keyboard       1899.00
Mouse           649.50
USB-C cable     299.00
TOTAL          2847.50

How the code works

  1. new PrintStream(file, StandardCharsets.UTF_8) (Java 10) opens the file with an explicit charset.
  2. %-12s left-aligns the item name in 12 characters, and %9.2f right-aligns the price with two decimals.
  3. Locale.ROOT keeps the decimal point as ., whatever the computer's regional settings are.
  4. charset() (Java 18) confirms the charset in use.

6. Example: Errors Do Not Throw Exceptions

An order service writes notifications through a PrintStream. Here the destination always fails, like a full disk. The failure does not reach the caller as an exception.

SilentFailure.java
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

public class SilentFailure {
    public static void main(String[] args) {
        // A destination that always fails, like a full disk or a closed socket
        OutputStream broken = new OutputStream() {
            @Override
            public void write(int b) throws IOException {
                throw new IOException("disk full");
            }
        };

        PrintStream out = new PrintStream(broken);
        boolean thrown = false;
        try {
            out.println("Order 501 shipped");      // the write fails inside PrintStream...
            out.flush();
        } catch (RuntimeException e) {
            thrown = true;
        }
        System.out.println("Exception thrown: " + thrown);   // ...but nothing reaches the caller
        System.out.println("checkError():     " + out.checkError());
    }
}
Output
Exception thrown: false
checkError():     true

How the code works

  1. The anonymous OutputStream throws an IOException for every byte.
  2. println() catches that exception internally and only records that an error happened.
  3. checkError() returns true, which is the only way to learn about the failure.

This makes PrintStream convenient for console output, but risky for data that must not be lost. Call checkError() when it matters.

7. PrintStream vs PrintWriter

AspectPrintStreamPrintWriter
FamilyByte stream (OutputStream)Character stream (Writer)
Typical useSystem.out, console and loggingWriting text files and responses
Raw bytesCan write bytes as well as textText only
Error handlingNo exceptions; checkError()No exceptions; checkError()

For new text output, PrintWriter is usually the better fit.

8. Common Mistakes and Best Practices

  • Assuming writes succeeded. Check checkError() for important output.
  • Relying on the default charset. Pass a Charset to the constructor.
  • Using locale-sensitive formats in files. Pass Locale.ROOT to printf for machine-readable numbers.
  • Closing System.out. Later console output would be lost.

9. Java Version Improvements and Java 25 Updates

Java versionChange
Java 1.0PrintStream with print()/println().
Java 5printf(), format(), append() and file constructors.
Java 10Constructors that take a Charset.
Java 14writeBytes(byte[]).
Java 18charset(); UTF-8 becomes the default charset (JEP 400).
Java 25No API changes. The new java.lang.IO.println() offers simple console output for beginners.

10. Summary

  • PrintStream prints values as text bytes; System.out is one.
  • It offers print, println and printf, and can flush automatically.
  • It never throws IOException; use checkError() to detect failures.
  • Pass a charset explicitly, and prefer PrintWriter for new text output.

Related Tutorials

11. Official Java Documentation References