Java System setOut() Method

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

Definition

In Java, System.setOut(stream) replaces the standard output stream. After the call, System.out refers to the PrintStream you passed, so every later System.out.println, in your code and in any library, writes there instead of to the screen.

The classic use is capturing output: send it into a ByteArrayOutputStream, then read the text back as a String. This is how tests check what a method prints. Because the change affects the whole program, save the original stream first and put it back in a finally block.

A static method of the java.lang.System class, added in Java 1 (JDK 1.1). Call it on the class name, as in System.setOut(...). No import is needed, because classes in java.lang are always visible.

Syntax

Save the original, redirect, and always restore:

Java
PrintStream original = System.out;
System.setOut(new PrintStream(buffer, true));  // buffer is a ByteArrayOutputStream
try {
    // code that prints
} finally {
    System.setOut(original);
}
CallWhat it does
System.setOut(new PrintStream(buffer, true))Send output into memory; true turns on auto-flush.
System.setOut(new PrintStream("log.txt"))Send output into a file (this constructor throws FileNotFoundException).
System.setOut(original)Put the saved stream back.

Added in Java 1.1. System.out is a final field, so setOut is the only supported way to replace it.

Library declarations
Java
// java.lang.System
public static void setOut(PrintStream out)

Parameters

ParameterDescription
outThe new standard output stream, usually a PrintStream wrapped around a buffer or a file.

Return Value

Return ValueDescription
voidNothing. The effect is that System.out now points to out.

Compare with Similar Methods

Related ways to control where text goes:

MethodHow it differs
setErr(stream)Replaces System.err, the error stream, instead.
setIn(stream)Replaces System.in, so reading code gets prepared input.
System.out.flush()Pushes buffered text out without changing the stream.
java App > out.txtRedirects output from the shell, with no code change.

Java Examples

Example 1 — Capture System.out into a String

Redirect the output into memory for one call, restore the screen, then show what was caught.

Java
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

public class SystemSetOutCapture {
    public static void main(String[] args) {
        PrintStream original = System.out;
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        System.setOut(new PrintStream(buffer, true));
        try {
            System.out.print("This line goes into the buffer");
        } finally {
            System.setOut(original);
        }

        String captured = buffer.toString();
        System.out.println("Captured: " + captured);
        System.out.println("Length: " + captured.length());
    }
}

How It Works

  1. Keep a way back. The program stores the screen stream in original before anything changes, because after setOut the field System.out no longer leads to the screen.
  2. Printing into memory. While redirected, System.out.print writes the bytes into buffer, so nothing appears on screen. print is used instead of println so no line break is stored.
  3. Reading the result. The finally block restores the screen, and buffer.toString() turns the 30 captured bytes into the 30-character text that the last two lines display.

Example 2 — Check What a Method Prints, Test Style

A method that prints instead of returning is hard to test. Capturing System.out turns its output into a value you can compare.

Java
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

public class SystemSetOutTest {
    static void greet(String name) {
        System.out.println("Hello, " + name + "!");
    }

    static String captureGreeting(String name) {
        PrintStream original = System.out;
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        System.setOut(new PrintStream(buffer, true));
        try {
            greet(name);
        } finally {
            System.setOut(original);
        }
        return buffer.toString().trim();
    }

    public static void main(String[] args) {
        String[] names = {"Ana", "Ben"};
        for (String name : names) {
            String text = captureGreeting(name);
            String expected = "Hello, " + name + "!";
            System.out.println((text.equals(expected) ? "PASS: " : "FAIL: ") + text);
        }
    }
}

How It Works

  1. A helper owns the redirect. captureGreeting swaps the stream, calls greet, and restores the screen even if greet threw, so main never sees a redirected System.out.
  2. Line breaks removed. println ends the captured text with "\n" or "\r\n" depending on the computer. trim() strips either one, so the comparison works on every system.
  3. Comparing like a unit test. Each captured greeting is checked against the expected text with equals; both match, so the loop prints PASS twice. Test frameworks such as JUnit use the same idea.

Example 3 — Hide Output from a Noisy Method

Point System.out at a stream that only counts bytes, run the chatty code, then switch the screen back on.

Java
import java.io.OutputStream;
import java.io.PrintStream;

public class SystemSetOutSilence {
    static class CountingStream extends OutputStream {
        int count;

        @Override
        public void write(int b) {
            count++;
        }
    }

    static void noisyWork() {
        for (int i = 0; i < 3; i++) {
            System.out.print("loading...");
        }
    }

    public static void main(String[] args) {
        PrintStream original = System.out;
        CountingStream counter = new CountingStream();
        System.setOut(new PrintStream(counter));
        try {
            noisyWork();
        } finally {
            System.out.flush();
            System.setOut(original);
        }
        System.out.println("Hidden bytes: " + counter.count);
        System.out.println("Back on screen: yes");
    }
}

How It Works

  1. A stream that throws text away. CountingStream extends OutputStream and only overrides write(int b), which adds one to count per byte and stores nothing.
  2. Thirty bytes vanish. noisyWork prints "loading..." (10 characters) three times. The text goes through the PrintStream into the counter, so 30 bytes are counted and none reach the screen.
  3. Flush, then restore. flush() makes sure every byte has reached the counter before finally restores the screen. Only the two summary lines are visible.

Frequently Asked Questions

Create a ByteArrayOutputStream, call System.setOut(new PrintStream(buffer, true)), run the code, restore the original stream, and read buffer.toString().
Save it first with PrintStream original = System.out; and call System.setOut(original) in a finally block so it is restored even after an exception.
System.out is declared final, so it cannot be assigned in normal code. System.setOut changes it through the JVM, which is the supported way.
Yes. All code that prints with System.out, including libraries, uses the new stream.
No. Error output stays where it was. Use System.setErr to redirect it.

Next: setProperties()

Replace the whole set of system properties, or reset it with null.

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

10 people found this page helpful