0
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?

7
  • Note that you could do 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. Commented Aug 8, 2014 at 20:19
  • Of course, even if x were not static, but were instead initialized in the constructor you'd get the same thing. Commented Aug 8, 2014 at 20:20
  • It would also work (given x is static) to do H nullH = null; System.out.print(nullH.x);. Commented Aug 8, 2014 at 20:24
  • @HotLicks what do you mean by javac compiler fakes the static reference?? Commented Aug 8, 2014 at 20:27
  • why nullH.x would work?? Commented Aug 8, 2014 at 20:28

3 Answers 3

2

Static variables are initialized before static blocks are executed. x is defined with a value of 0 because it's a primitive. Then it is assigned the value of 2.

Sign up to request clarification or add additional context in comments.

Comments

0

The static blocks are executed when the class is loaded. This happens before your code can create an instance of the class, so by the time new H() executes the value is already initialized. Also, you should not refer to static members with an instance reference. It should just be H.x.

1 Comment

I'm not sure one can say "should not" when javac goes out of its way to fake things if you use a reference rather than a class to refer to a static.
0

how does compiler works because till that time we do not have definition of x

x is defined as a static field of H class:

public class H{
    //here is the definition of x static field
    //is uninitialized but that's not a problem for the compiler
    static final int x;
    static {
        //...
    }
}

Apart of that, all fields in a class are initialized with a default value. int fields are initialized with 0. This enables using H.x in any part of the code and being compilable.

About execution, check @JimGarrison's answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.