0

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

Sunil Kumar
  • 76
  • 1
  • 13

2 Answers2

1

They are different streams and they flushed at different times.

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

You can take help from this Stack-question

Community
  • 1
  • 1
unknownbits
  • 2,855
  • 10
  • 41
  • 81
1

They are different streams and are flushed at different times.

If you put

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

Inside your code, it will work as expected.

Dsenese1
  • 1,106
  • 10
  • 18