public class Test {
private static final int A;
static {
A = 5;
}
}
This way of initializing static final variable A works okay .
public class Test {
private static final int A;
static {
Test.A = 5;
}
}
This way gives compile error "Cannot assign a value to final variable 'A'.
Why?
But in some cases it generates code that uses two guard variables and initialize each static variable separately. The problem is when such two types of initialization are mixed in executable binary. In such case it may happen that second static variable will get initialized twice.
The only way to initialize static final variables other than the declaration statement is Static block. A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of class loading.
Static variables can be assigned as many times as you wish.
Static variables can be accessed by calling with the class name ClassName. VariableName. When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.
Specified by the rules for Definite Assignment:
Let C be a class, and let V be a blank
static final
member field of C, declared in C. Then:
V is definitely unassigned (and moreover is not definitely assigned) before the leftmost enum constant, static initializer (§8.7), or static variable initializer of C.
V is [un]assigned before an enum constant, static initializer, or static variable initializer of C other than the leftmost iff V is [un]assigned after the preceding enum constant, static initializer, or static variable initializer of C.
In layman's terms:
Using a static initializer to initialize a static final
field by referencing its simple name is OK since that field is definitely assigned after the initializer. Effectively, there's context into the class in which the static initializer is declared in, and you are not performing any illegal assignment by referring to the field by its simple name; instead, you're fulfilling the requirement that the field must be definitely assigned.
Using a static initializer to initialize a static final
field by referencing its qualified name is illegal, since the class must be initialized when referring to a static property of it (in your case, Test.A
must be initialized prior, and A
is assigned the default value of null
upon completion of initialization).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With