Search code examples
javastaticfinal

Why is the static initializer not executed if referenced static field is final


class a
{
    static final  int a =5;
    static {
        System.out.println("hi");

    }
}
class b
{
    public static void main(String[] args) {
        System.out.println(a.a);
    }   

}

Why doesn't the static block run,and the output is only

5

whereas if I remove final keyword from the class variable, the static block gets executed and the output becomes

hi 
5

Solution

  • Basically what happened is that the static final combination on primitives and Strings cause them to be inlined by the compiler, and this might have prevented the static initialization block from execution, since a class is never loaded by the classloader, as a.a was resolved during compilation