Static Initializations Flashcards
Give me the definition of a static initializer !
A static initializer is a block of code preceded by the keyword static, which is used for initializing static variables and performing any static initialization when the class is first loaded
Give me a characteristic of the static initializer !
The characteristic of the static initializer is that it runs before any code in the class when the class is first loaded by the JVM.
Give me when a static final variable should be initialized with examples and counter-examples !
A static final variable should be initalized inline or inside a static initializer, it can not be initialized in a constructor or in an instance initializer because that will result in a compilation error
EXAMPLE 1 :
public class Example {
static final int STATIC_FINAL_VAR = 10;
}
EXAMPLE 2 :
public class Example {
static final int STATIC_FINAL_VAR;
static { STATIC_FINAL_VAR = 10; } }
**COUNTER-EXAMPLE ** :
public class Example {
static final int STATIC_FINAL_VAR;
// This would cause a compilation error { STATIC_FINAL_VAR = 10; } // This would also cause a compilation error public Example() { STATIC_FINAL_VAR = 10; } }
What is the difference between a static final variable and final variable with examples !
A static final variable can only be initialized inline or inside a static initializer while a final variable can be initialized inline, in an instance initializer, or in a constructor
When a final instance variable should be initialized with examples and counter examples !
A final instance variable should be initialized inline or in an instance initializer or in a constructor and that’s it
EXAMPLE 1 :
public class Example {
final int finalInstanceVarInline = 10; // Initialized inline
final int finalInstanceVarInitializerBlock; { finalInstanceVarInitializerBlock = 20; // Initialized in an instance initializer block } final int finalInstanceVarConstructor; public Example(int value) { finalInstanceVarConstructor = value; // Initialized in a constructor }
EXAMPLE 2 :
14 :private static int one;
15 : private static final int two;
16 : private static final int three = 3;
17 : private static final int four; /* DOES NOT COMPILE */
18 : static {
19 : one = 1;
20 : two = 2;
21 : three = 3; // DOES NOT COMPILE
- Line 14 declares a static variable that is not final. It can be assigned as many times as we like
- Line 15 declares a final variable without initializing it. This means we can initialize it exactly once in a static block.
- Line 21 doesn’t compile because this is the second attempt.
- Line 17 declares a final variable that never gets initialized