I know that static blocks are run before anything. But here, what happens when B.test() is called? Order of execution and setting of values? Later, when b1 is set to null, still how b1.i evaluates to 20?
class B
{
static int i;
static {
i = 20;
System.out.println("SIB");
}
static int test() {
int i = 24;
System.out.println(i);
return i;
}
}
public class Manager {
public static void main(String[] arg) {
B.test();
B b1 = null;
System.out.println(b1.i);
}
}
The output is:
SIB
24
20
iis static, sob1.iis equivalent toB.i. Just settingb1tonulldoesn’t change any static variables.When
B.test()is called, first theBclass is loaded, and the static blocks are run. Next,B.test()creates a new method-local variable calledi, which is completely different fromB.i. This new, localiis printed and returned. No changes are made toB.i, and certainly not just because you created a newBobject reference that was null — that would never have any effect on anything.