My guess is that your field is of either a primitive type or String
, and is initialized with a compile-time constant expression.
For static final fields initialized with a constant expression (and only such fields) - any code which refers to the field will have the constant value baked into it, rather than going via the static field which would cause class initialization. The "constant expression" part is important though. We can see this with a small test app:
class Fields {
public static final String CONSTANT = "Constant";
public static final String NON_CONSTANT = new String("Non-constant");
static {
System.out.println("Initializing");
}
}
public class Test {
public static void main(String arg[]) {
System.out.println(Fields.CONSTANT);
System.out.println(Fields.NON_CONSTANT);
}
}
The output is:
Constant
Initializing
Non-constant
Accessing the constant field does not require initialization, but accessing the non-constant one does. Using a non-final field would have the same effect: it would no longer count as a constant, basically.
The information about "this is a constant" gets baked into the class declaring a field. For example, using javap -c Fields
we see the two fields:
public static final java.lang.String CONSTANT;
flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL
ConstantValue: String Constant
public static final java.lang.String NON_CONSTANT;
flags: ACC_PUBLIC, ACC_STATIC, ACC_FINAL
Note the ConstantValue
part of the CONSTANT
field metadata, which is missing from the NON_CONSTANT
field metadata.
See section 15.28 of the JLS for more on what constitutes a constant expression.
Section 12.4.1 of the JLS specifies when a class is initialized:
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant variable (§4.12.4).
T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
(Emphasis mine.)