如果我们使用 err.println(); ,为什么输出顺序每次都会更改? 有时,静态块首先执行,有时是初始化块, 但是如果将 err 替换为 out ,则静态块将始终首先执行。
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");
}
}
错误输出: 第一个输出:
The BUG.... :-) 1
The BUG.... :-) 2
The BUG.... :-) 3
The BUG.... :-) 4
The BUG.... :-) 5
Static block 1
Static block 2
Static block 3
第二个输出:
Static block 1
Static block 2
Static block 3
The BUG.... :-) 1
The BUG.... :-) 2
The BUG.... :-) 3
The BUG.... :-) 4
The BUG.... :-) 5
没有err.print只能获得以下输出:
Static block 1
Static block 2
Static block 3
The BUG.... :-) 1
The BUG.... :-) 2
The BUG.... :-) 3
The BUG.... :-) 4
The BUG.... :-) 5
谢谢
Sumitkrroxit