It is well known that when accessing a variable or method of a class, if the class is not initialized, a class is initialized first.
However, when the variable of this class is final, it is not necessarily
Take a look at the following example
Package Com.lala.shop;import Java.util.random;public class App {public    static void Main (string[] args)    {        System.out.println (USER.C);    }} Class User{public static final int b = new Random (). Nextint (one);p ublic static final int c = 20;STATIC{SYSTEM.OUT.PRINTLN (" User static init ... ");}
When accessing
System.out.println (USER.C);
, there is no output of "User static init ..."
Because C is a static final variable, and it is equal to 20, you can know its value at compile time, so accessing the value of a directly does not cause the initialization of the user class.
When accessing
System.out.println (USER.B);
, the output is "User static init ..."
This static final variable B is not known for its exact value at compile time, so it can only be known until it is run, so it accesses
USER.B will cause initialization of the user class. That is, static code is loaded quickly.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
The effect of the final keyword on the JVM class loader