Java PrintStream

Su Suriya Ravichandran Updated 18 Nov 2026
8 min read ·Lesson 152 of 306

What PrintStream Is

java.io.PrintStream is an output stream that can print values of any type as text. You've used it in every Java program: System.out and System.err are both PrintStream objects.

System.out.println("Hello");   // System.out is a PrintStream

A plain OutputStream only writes bytes. PrintStream sits on top of one and adds:

  • print and println methods for every primitive type, String, char[] and Object,
  • formatted output with printf and format,
  • conversion of characters to bytes using a charset,
  • optional automatic flushing,
  • no checked exceptions: errors are recorded internally instead of being thrown.

That last point is a deliberate design decision. Printing happens everywhere — debugging, logging, progress messages — and forcing every println to handle IOException would be impractical. The consequence is that PrintStream is convenient for console output but needs care when the output really matters, as this lesson shows.

Printing Values

import java.util.*;

public class P1 {
    public static void main(String[] args) {
        System.out.println("System.out is a " + System.out.getClass().getName());
        System.out.print("no newline, ");
        System.out.print(42);
        System.out.println();
        System.out.println(3.0 / 4);
        System.out.println('A' + 1);
        System.out.println("" + 'A' + 1);
        char[] letters = {'J', 'a', 'v', 'a'};
        System.out.println(letters);
        System.out.println("letters: " + Arrays.toString(letters));
        Object nothing = null;
        System.out.println(nothing);
        System.out.println(List.of("pen", "ink"));
        System.out.printf("%-8s|%6.2f|%,d%n", "total", 1234.5, 1_000_000);
        System.out.format(Locale.GERMANY, "%,.2f%n", 1234.5);
        System.out.append("append ").append('x').append("\n");
    }
}

Output (in an English locale):

System.out is a java.io.PrintStream
no newline, 42
0.75
66
A1
Java
letters: [J, a, v, a]
null
[pen, ink]
total   |1234.50|1,000,000
1.234,50
append x

What each line shows:

CodeBehaviour
print(x)Writes the text form of x, without a line break
println() / println(x)Writes x (if given) followed by the platform line separator (\n or \r\n)
println('A' + 1)'A' + 1 is int arithmetic (65 + 1), so 66 is printed. Starting with "" makes it string concatenation: A1
println(char[])Has its own overload that prints the characters (Java). Any other array prints as a type code and hash, which is why Arrays.toString is used for display
println(null object)Prints null instead of throwing — print(Object) uses String.valueOf(obj)
println(List.of(...))Calls the object's toString()
printf / formatFormatted output using the same syntax as String.format. %-8s left-aligns in 8 characters, %6.2f gives two decimals in 6 characters, %,d adds grouping separators, %n writes the platform line separator
format(Locale, ...)Formats for a specific locale: German uses . for grouping and , for decimals
append(...)From the Appendable interface; returns the stream so calls can be chained

Use %n rather than \n in format strings when the output should follow the platform's line-ending convention.

How print Converts Text to Bytes

A PrintStream writes bytes, so text is encoded with a charset. For System.out and System.err, Java chooses the charset from the terminal environment; since Java 19 you can read it with System.getProperty("stdout.encoding") and override it with -Dstdout.encoding=UTF-8. If a terminal is set to a charset that can't represent a character (for example the ₹ sign on an old Windows console code page), it's printed as ?. That isn't a bug in your string — it's the output encoding.

For PrintStreams you create yourself, always pass the charset explicitly.

Creating a PrintStream for a File

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;

public class P2 {
    public static void main(String[] args) throws IOException {
        try (PrintStream report = new PrintStream(new FileOutputStream("report.txt"), false, StandardCharsets.UTF_8)) {
            report.println("Monthly report");
            report.printf("%-10s %10s%n", "Course", "Revenue ₹");
            report.printf("%-10s %,10d%n", "Java", 48250);
        }
        System.out.print(Files.readString(Path.of("report.txt")));

        PrintStream broken = new PrintStream(new OutputStream() {
            @Override public void write(int b) throws IOException {
                throw new IOException("disk full");
            }
        }, true);
        broken.println("this line is lost");
        System.out.println("no exception was thrown; checkError() = " + broken.checkError());
    }
}

Output:

Monthly report
Course      Revenue ₹
Java           48,250
no exception was thrown; checkError() = true

Constructors

ConstructorUse
new PrintStream(OutputStream out, boolean autoFlush, Charset cs)Wrap any byte stream with an explicit charset (Java 10+)
new PrintStream(String fileName, Charset cs) / new PrintStream(File file, Charset cs)Create or truncate a file directly (Java 10+)
new PrintStream(OutputStream out)Platform default charset, no auto-flush

Auto-flush. With autoFlush = true, the stream flushes after every println, whenever a byte array is written, and whenever a newline character is written (so a printf ending in %n is flushed too). That's what makes console messages appear immediately. For files, leaving it false is faster; closing the stream flushes everything.

Errors are swallowed

The second part of the example connects a PrintStream to an OutputStream that always fails, as a full disk or a closed network connection would. println doesn't throw. The PrintStream catches the IOException, sets an internal error flag, and carries on. The only way to find out is checkError(), which flushes the stream and returns true if any error has occurred.

That makes PrintStream (and its character-based cousin PrintWriter) a poor choice for output whose loss would matter, such as an export or a data file. Either call checkError() before closing, or use a BufferedWriter/OutputStream, which throw IOException immediately.

System.out and System.err

System.outSystem.err
StreamStandard outputStandard error
Intended forThe program's resultsErrors, warnings, diagnostics
Redirected by > fileYesNo (needs 2> file)

Keeping them separate lets users redirect results to a file while still seeing error messages on screen. Because they're independent streams, their output can appear in a slightly different order on screen than the order of the calls.

Redirecting System.out

System.setOut(PrintStream) and System.setErr(PrintStream) replace the standard streams for the whole JVM. The classic use is capturing output in tests:

import java.io.*;
import java.nio.charset.StandardCharsets;

public class P3 {
    static void greet(String name) {
        if (name.isBlank()) {
            System.err.println("warning: empty name");
            return;
        }
        System.out.println("Hello, " + name + "!");
    }

    static String captureOut(Runnable code) {
        PrintStream original = System.out;
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        try (PrintStream capture = new PrintStream(buffer, true, StandardCharsets.UTF_8)) {
            System.setOut(capture);
            code.run();
        } finally {
            System.setOut(original);
        }
        return buffer.toString(StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        String out = captureOut(() -> greet("Asha"));
        System.out.println("captured: [" + out.strip() + "]");
        System.out.println("test " + (out.equals("Hello, Asha!" + System.lineSeparator()) ? "PASSED" : "FAILED"));
        String none = captureOut(() -> greet(" "));
        System.out.println("captured for blank name: [" + none + "]");
    }
}

Output (the warning comes from System.err, which wasn't redirected):

captured: [Hello, Asha!]
test PASSED
warning: empty name
captured for blank name: []

How it works:

  1. Save the original System.out before replacing it.
  2. Redirect to a PrintStream over a ByteArrayOutputStream, which collects everything printed in memory.
  3. Run the code under test. Its System.out.println calls now go into the buffer.
  4. Restore the original in finally, so the rest of the program prints normally even if the code throws. Forgetting this leaves the whole JVM printing into a buffer nobody reads.
  5. Compare the captured text. The expected value uses System.lineSeparator(), because println writes the platform separator — "Hello, Asha!\n" would fail on Windows.

For the blank name, nothing is written to System.out; the warning goes to System.err and appears directly on the console.

System.setOut affects every thread in the JVM, so tests that capture output shouldn't run in parallel with others that print. In real projects, a better design is to pass a PrintStream (or a Writer) into the code as a parameter, so tests can supply their own without touching global state.

Practical Example: Writing Output to the Console and a Log File

Batch jobs often need their progress messages both on screen (for whoever runs the job) and in a log file (for later investigation). A small OutputStream that forwards every byte to two destinations — a tee, named after the Unix tee command — achieves this without changing any of the job's println calls.

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import static java.nio.file.StandardOpenOption.*;

public class Tee {
    static class TeeOutputStream extends OutputStream {
        private final OutputStream first, second;
        TeeOutputStream(OutputStream first, OutputStream second) {
            this.first = first;
            this.second = second;
        }
        @Override public void write(int b) throws IOException { first.write(b); second.write(b); }
        @Override public void write(byte[] b, int off, int len) throws IOException {
            first.write(b, off, len);
            second.write(b, off, len);
        }
        @Override public void flush() throws IOException { first.flush(); second.flush(); }
        @Override public void close() throws IOException {
            try { second.close(); } finally { first.flush(); }   // never close the real console
        }
    }

    public static void main(String[] args) throws IOException {
        Path log = Path.of("job.log");
        PrintStream console = System.out;
        OutputStream file = Files.newOutputStream(log, CREATE, TRUNCATE_EXISTING);
        try (PrintStream both = new PrintStream(new TeeOutputStream(console, file), true, StandardCharsets.UTF_8)) {
            System.setOut(both);
            System.out.println("import started");
            System.out.printf("processed %d rows%n", 1250);
            System.out.println("import finished");
        } finally {
            System.setOut(console);
        }
        System.out.println("--- job.log contains ---");
        System.out.print(Files.readString(log));
    }
}

Output:

import started
processed 1250 rows
import finished
--- job.log contains ---
import started
processed 1250 rows
import finished

Step by step:

  1. TeeOutputStream extends OutputStream. Only write(int) is required, but overriding write(byte[], int, int) passes whole blocks along at once instead of byte by byte, which matters for performance.
  2. flush flushes both destinations, so with auto-flush enabled each line reaches the console and the file immediately.
  3. close closes only the file. The console stream belongs to the JVM; closing it would make every later System.out.println in the program silently print nothing. It's only flushed. The try/finally ensures the flush happens even if closing the file fails.
  4. System.setOut(both) sends all standard output through the tee. The job's code doesn't change at all — it still calls System.out.println.
  5. try-with-resources closes the PrintStream, which closes the tee, which closes the log file. finally then restores the original System.out.
  6. The log file contains exactly what was shown on screen.

For applications rather than one-off jobs, a logging framework (SLF4J with Logback or Log4j 2) is the better tool: it writes to several destinations, adds timestamps and levels, rotates files and can be configured without code changes. But knowing how PrintStream and stream wrapping work explains what those frameworks do underneath, and is the right tool for small utilities and tests.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java PrintStream and get answers drawn from it.

Signed-in readers only.