The final static field variable is a constant variable. There is only one copy of this variable available. It is mandatory to initialize the final static field variable explicitly as the default value for it is not provided by the JVM. Also, this variable cannot be reinitialized.
A program that initializes the final static field variable using a static initialization block is given as follows:
Example
Live Demo
public class Demo {
final static int num;
static {
System.out.println("Running static initialization block.");
num = 6;
}
public static void main(String[] args) {
System.out.println("num = " + num);
}
}
Output
Running static initialization block.
num = 6
Now let us understand the above program.
The class Demo contains the final static field variable num. The static initialization block initializes num. Then the value of num is printed in the main() method. A code snippet which demonstrates this is as follows:
final static int num;
static {
System.out.println("Running static initialization block.");
num = 6;
}
public static void main (String [] args) {
System.out.println ("num = " + num);
}