Sunil Kumar Sunil Kumar - 2 months ago 15
Java Question

Unexpected output using System.err.println() in java

I tried executing the following print statements in JAVA, but the output which I got is unexpected. Output is jumbled.

public class AsyncTestClass {
public static void main(String[] args) {

System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println("4");
System.out.println("5");
System.err.println("Error");
System.out.println("6");
System.out.println("7");
System.out.println("8");
System.out.println("9");
System.out.println("10");
}
}


first run Output:

1
Error
2
3
4
5
6
7
8
9
10


second run output:

1
2
3
4
5
Error
6
7
8
9
10


third run output:

1
Error
2
3
4
5
6
7
8
9
10


Why I am getting different outputs for the same code??
Thanks

Answer

They are different streams and they flushed at different times.

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

You can take help from this Stack-question