public class H {
static final int x;
static {
x=2;
}
public static void main(String... args) {
System.out.print(new H().x);
}
}
This will print 2 as o/p.
Now my question is:
We know that the static block is called first. Now if the static block is called, we are having x=2 in that block. So how does the compiler works, because until that time we do not have definition of x?
System.out.print(H.x);and get the same result. The javac compiler fakes the static reference when you use an instance reference on a static value or method.xwere not static, but were instead initialized in the constructor you'd get the same thing.xis static) to doH nullH = null; System.out.print(nullH.x);.