Java Static Initializer Block

What is a Static Initializer Block in Java?

Java Static Initializer Block is similar to Instance Initializers, only it has the word static in front of the block.

class Vehicle {
  static {
    System.out.println("Static Initializer Block...");

It is called when the class is loaded, so only once. No matter how many times we create a new object.

Things to remember about Static Initializer Block:

  1. It is called before the main method, whether it’s declared after or before it.
  2. It will be executed only once when the class is loaded.
  3. If we have more than one, they will be executed in the order they appear in the class.
  4. It can initialize static variables
  5. It cannot access an instance variable, only a static one

Example 1:

 1  class Car {
 3    private static int one;
 4    private static final int two;
 5    private static final int three = 3;
 6    private static final int four; // DOES NOT COMPILE
 8    static {
 9      one = 1;
10      two = 2;
11      three = 3; // DOES NOT COMPILE
12      two = 4; // DOES NOT COMPILE
13    }
14  }

Line 3 declares a static variable that is not final. It can be assigned as many times as we like.

Line 4 declares a final variable without initializing it. This means we can initialize it exactly once in a static block.

Line 11 doesn’t compile because on line 5, we declared and initialized the final variable. Therefore, we are not allowed to assign it again.

Line 6 declares a final variable that never gets initialized.

The compiler gives a compiler error because it knows that the static blocks are the only place the final variable could get initialized.

Example 2:

If we try to access an instance variable from a static initializer, we get a compiler error.

class Car {
  private static int one;
  private int two;
  static {
    one = 1;
    two = 2; // DOES NOT COMPILE

Example 3:

class Car {
  private static String colour;
  static {
    colour = "blue";
    System.out.println("Static Initializer Block...");
  public static void main(String args[]) {
    System.out.println("Main method...");
Output: Static Initializer Block… Main method… blue

In the example above, you can see the order of execution.

First, the Static Initializer Block gets invoked, assigning value to a static variable colour.

After that, the main method gets executed, and we print the value of colour variable.

That was all regarding Java Static Initializer blocks. Proceed to the next lesson to learn more about keyword final in Java. 

Happy Learning!

Leave a Reply

Your email address will not be published.