1

I was reading about static initializer and came across this question

Why reference to a static final field will not trigger class loading?

I made a little modification of the class from that question:

public class Constants {
    public static final String c1;

    static {
        c1 = "C1";
        System.out.println("Constants Class Loaded!");
    }
}

Now it is printing:

Constants Class Loaded!
C1

It seems that when I am assigning value to the static final variable in static initializer block the static initializer is run. But it should not run because JLS says referring to constant static variables should not load class. Can anyone give an explanation?

Sattyaki
  • 376
  • 2
  • 9
  • 1
    Are you sure JLS isn't referring to "compile-time constants"? – biziclop Mar 28 '18 at 17:45
  • 1
    The final variable has to have a value, so it calls the static constructor to set that value, otherwise it would be permanently null. – vandench Mar 28 '18 at 17:46
  • 1
    The JLS notes the variable must be "initialized with a constant expression" - doing work in a `static { }` block means the assignment does not happen at compile-time, and therefore isn't a constant expression. – dimo414 Mar 28 '18 at 17:47
  • Since it’s a final variable it cannot have a default value. Thus, static initialiser is called to assign it a value when it is referred. This is mentioned in JLS. – Sahil Chhabra Mar 28 '18 at 18:03

0 Answers0