I am wondering when static variables are initialized to their default values.
Is it correct that when a class is loaded, static vars are created (allocated),
then static initializers and initializations in declarations are executed?
At what point are the default values are given? This leads to the problem of forward reference.
Also please if you can explain this in reference to the question asked on Why static fields are not initialized in time? and especially the answer given by Kevin Brock on the same site. I can’t understand the 3rd point.
From See Java Static Variable Methods:
Instance and class (static) variables are automatically initialized to standard default values if you fail to purposely initialize them. Although local variables are not automatically initialized, you cannot compile a program that fails to either initialize a local variable or assign a value to that local variable before it is used.
What the compiler actually does is to internally produce a single class initialization routine that combines all the static variable initializers and all of the static initializer blocks of code, in the order that they appear in the class declaration. This single initialization procedure is run automatically, one time only, when the class is first loaded.
In case of inner classes, they can not have static fields
See JLS 8.1.3 Inner Classes and Enclosing Instances
finalfields in Java can be initialized separately from their declaration place this is however can not be applicable tostatic finalfields. See the example below.This is because there is just one copy of the
staticvariables associated with the type, rather than one associated with each instance of the type as with instance variables and if we try to initializezof typestatic finalwithin the constructor, it will attempt to reinitialize thestatic finaltype fieldzbecause the constructor is run on each instantiation of the class that must not occur to staticfinalfields.