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