[英]How I am getting static instance variable with object of that class
[英]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.