This question already has an answer here:
Please consider this java code:
public class CMain {
public static void main(String[] args){
for (int i = 0; i < 10; i++) {
System.out.println("A");
System.err.println("B");
}
}
}
By a quick look at the code, some of us may think the output has to be the print of As and Bs alternatively. However is not! It is a random appearance of 10 A characters and 10 B ones. Something like this:
Why is that? and what is the solution for it so that the As and Bs gets displayed alternatively ( A B A B A B ...) Before I ask this question, I checked several other similar questions for solution and non worked for my case! I have brought some of them here:
They are different
OutputStream
s. If you really need to guarantee the order of printing them, use:or
This is because
out
anderr
are two different output streams. However, both of them print on console. So you do not see them as different streams. Moreover, when you doout.println()
, it is not guaranteed that you will see the output on the console as soon as the statement gets executed. Instead, the strings are usually(depends on the system) stored in an output buffer (if you will) which is processed later by the system to put the output from the buffer onto the screen.Although, as Eng.Fouad pointed out that you can use
setOut(System.err)
orsetErr(System.out)
to make them ordered, I would still not suggest doing that when you are actually putting this in an application (only use it for debugging purposes).What the proposed solution does is that it will end up using only one stream for both the standard output and the standard error, which I do not think is a good thing to do.
Since there are two separate streams, the output you are giving is possible.