Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 486
Nick Heiner Avatar asked Dec 10 '09 19:12

Nick Heiner


People also ask

What is the difference between system out system err and system in?

System. out is "standard output" (stdout) and System. err is "error output" (stderr). Along with System.in (stdin), these are the three standard I/O streams in the Unix model.

What happens when you use system out and system err?

out is "standard output" (stdout) and System. err is "error output" (stderr). If you are using a simple Java console application, both outputs will be the same (the command line or console) but you can reconfigure the streams so that for example, System. out still prints to the console but System.

What is the difference between system out Println and system out format?

The key difference between them is that printf() prints the formatted String into console much like System. out. println() but the format() method returns a formatted string, which you can store or use the way you want.


1 Answers

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

like image 80
Bill K Avatar answered Oct 01 '22 09:10

Bill K