为什么我会得到在静态和实例初始化程序块中分配的静态变量的输出?

Why am I getting this output for a static variable assigned in both static and instance initializer blocks?

我在面试中得到了以下代码。

为什么输出是2?

public class Test {
    static int a = 1111;
    static {
        a = a-- - --a;
    }

    {
        a = a++ + ++a;
    }

    public static void main(String[] args) {
        System.out.println(a);
    }
}

static变量a初始化为1111

然后是静态初始化器运行s。 a-- 的计算结果为 1111,但将 a 设置为 1110。然后 --a 运行s,将 a 设置为 1109 并计算为 1109。减法发生,a 被设置为减法的结果,2.

实例初始化器(使用 ++ 运算符)没有 运行,因为没有 Test 的实例。 2 被打印出来。

为了理解逻辑,在静态块中添加以下代码和运行:

int b = a--;
System.out.println("Now b is   " + b);
System.out.println("Now a is   " + a);
int c = --a;
System.out.println("Now c is  " + c);
System.out.println("Now a is  " + a);

a = b-c; //1111 - 1109 = 2
System.out.println("a =  " + a);

将打印:

b =  1111
a =  1110
c =  1109
a =  1109
a =  2