Why does this code print 2 and not 1?
The System.out is using A.i not a.i (in which case it would make sense to get the instance value of i = 2 since it would be using the instance a).
class A {
static int i = 1;
{i = 2;}
}
class B {
public static void main(String[] args) {
A a = new A();
System.out.println(A.i);
}
}
>Solution :
This line in class A
{i = 2;}
is called an "initialization block" (some good discussion about them here). It is very similar to a constructor, in that the code in that block will be executed when a new instance is created. There is more to it than that, but for the purpose of your question, that’s really all you need to know.
So when you create a new instance of class A, that block runs, and it sets the (static) field i to the value 2. Since i is static, there is only ever 1 value, which is always set to 2.
Perhaps you mean for i to be an instance field? If so, remove the static modifier from its declaration. Note that even if you do that, i will still have the value 2 since the initialization block runs after the inline inialization.