0

Why is the output sequence changing every time, if we are using err.println(); ? Sometimes the static block executes first, sometimes the initialization block, but if we replace err with out, static block always executes first.

import static java.lang.System.out;
import static java.lang.System.err;

public class TestStatic{

    static int x = 0;
    static {
        out.println("Static block  1");
    }

    {
        err.println("The BUG.... :-) "+ (++x) );
    }

    static {
        out.println("Static block  2"); 
    }

    public static void main(String args[]) {
        TestStatic obj1 =  new TestStatic();
        TestStatic obj12 =  new TestStatic();
        TestStatic obj13 =  new TestStatic();
        TestStatic obj14 =  new TestStatic();
        TestStatic obj15 =  new TestStatic();

    }
static {
    out.println("Static block  3"); 
   }    
}

output with err: 1st output:

The BUG.... :-) 1 
The BUG.... :-) 2 
The BUG.... :-) 3 
The BUG.... :-) 4 
The BUG.... :-) 5 
Static block  1 
Static block  2 
Static block  3 

2nd Output:

Static block  1 
Static block  2 
Static block  3 
The BUG.... :-) 1 
The BUG.... :-) 2 
The BUG.... :-) 3 
The BUG.... :-) 4 
The BUG.... :-) 5 

Without err.print getting below output only:

Static block  1 
Static block  2 
Static block  3 
The BUG.... :-) 1 
The BUG.... :-) 2 
The BUG.... :-) 3 
The BUG.... :-) 4 
The BUG.... :-) 5

Thanks,

Sumitkrroxit

  • 7
    Because not all streams (and buffering) are created equal. – Dave Newton Aug 20 '18 at 18:15
  • 5
    The only way to ensure that output is printed in correct sequence, is to only use one print stream. When you use two print streams, some of the output may be buffered and hence delayed until the stream is flushed. – Andreas Aug 20 '18 at 18:20
  • You can also try `System.err.flush()` after printing to see how that affects the output. – Kayaman Aug 20 '18 at 18:21
  • Did you mean `System.out.flush()` here, @Kayaman? That would make more sense in this context :-) – Dirk Aug 20 '18 at 18:21
  • @Dirk not really. I trust that the reader will also try that with `System.out`. – Kayaman Aug 20 '18 at 18:22

0 Answers0