簡體   English   中英

為什么在靜態和實例初始化程序塊中分配的靜態變量都得到此輸出?

[英]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

然后,靜態初始化程序將運行。 a--值為1111但將a設置為1110 然后--a運行,將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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM