public class DemoApplication {
public static void main(String[] args) {
System.out.println("count: "+A.count);
System.out.println("count: "+A.count);
var a1=new A();
var a2=new A();
System.out.println("count: "+A.count);
}
}
1)
public class A {
public static A inst = new A();
public static int count;
public A() {
A.inst.count++;
}
}
output:
count: 1
count: 1
count: 3
2)
public class A {
public static A inst = new A();
public static int count=0;
public A() {
A.inst.count++;
}
}
output:
count: 0
count: 0
count: 2
The differences is in
- public static int count;
- public static int count=0;
Can anyone explain this?
>Solution :
Static initialization occurs in order.
In your first code snippet, the first action is to create a new instance of A
for the static field. It needs the static field so that gets initialized to the default value, 0. The constructor then increases it to 1.
In your second code snippet, after the initialization of the static field, the value (1) is reset back to 0.