System.out.println and System.err.println out of order

Nick Heiner picture Nick Heiner · Dec 10, 2009 · Viewed 21.1k times · Source

My System.out.println() and System.err.println() calls aren't being printed to the console in the order I make them.

public static void main(String[] args) {
    for (int i = 0; i < 5; i++) {
        System.out.println("out");
        System.err.println("err");
    }
}

This produces:

out
out
out
out
out
err
err
err
err
err

Instead of alternating out and err. Why is this?

Answer

Bill K picture Bill K · Dec 10, 2009

They are different streams and are flushed at different times.

If you put

System.out.flush();
System.err.flush();

inside your loop, it will work as expected.

To clarify, output streams are cached so all the write goes into this memory buffer. After a period of quiet, they are actually written out.

You write to two buffers, then after a period of inactivity they both are flushed (one after the other).