A.f()
in triggers initialization of class .App.main()
A
All constant variables are initialized. The only constant variable is , which now is .S1
1
Then, the other static fields are initialized in textual order. is the first field, which triggers initialization of class , which in turn calls . is simply because it is not initialized yet. Initialization of is now complete. Last but not least, is initialized to the object .b
B
A.f()
S2
null
b
S2
Integer
2
S2
is not a constant variable because it is not of the primitive type but of the reference type . is an auto-boxing shorthand for .int
Integer
S2 = 2;
S2 = Integer.valueOf(2);
If a declarator in a field declaration has a variable initializer, then the declarator has the semantics of an assignment (§15.26) to the declared variable.
[…]
Note that fields that are constant variables (§4.12.4) are initialized before other fields (§12.4.2). This also applies in interfaces (§9.3.1). Such fields will never be observed to have their default initial values (§4.12.5), even by devious programs.static
static
8.3.2. Field Initialization
A constant variable is a variable of primitive type or type that is initialized with a constant expression (§15.28). Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9), and definite assignment (§16 (Definite Assignment)).final
String
4.12.4. final
Variables
A constant expression is an expression denoting a value of primitive type or a that does not complete abruptly and is composed using only the following:String
- Literals of primitive type and literals of type
String
[…]
15.28. Constant Expressions
For each class or interface C, there is a unique initialization lock . The mapping from C to is left to the discretion of the Java Virtual Machine implementation. The procedure for initializing C is then as follows:LC
LC
[…]
-
Otherwise, record the fact that initialization of the object for C is in progress by the current thread, and release .Class
LC
Then, initialize the fields of C which are constant variables (§4.12.4, §8.3.2, §9.3.1).static
[…]
- Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.
12.4.2. Detailed Initialization Procedure
Every variable in a program must have a value before its value is used:
-
Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10.2):
[…]
- For all reference types (§4.3), the default value is .
null
4.12.5. Initial Values of Variables