Java - static Initialization Block

What is static Initialization Block

A static initialization block initializes class variables.

An instance initializer is executed once per object whereas a static initializer is executed only once for a class when the class definition is loaded into JVM.

Syntax

To differentiate it from an instance initializer, use the static keyword in the beginning of its declaration.

You can have multiple static initializers in a class.

All static initializers are executed in textual order in which they appear, and execute before any instance initializers.

Rule

A static initializer cannot throw checked exceptions and it cannot have a return statement.

Demo

public class Main {
  private static int num;

  // An instance initializer
  {// w  ww  .  jav  a 2  s. c om
    System.out.println("Inside instance initializer.");
  }

  // A static initializer. Note the use of the keyword static below.
  static {
    num = 1245;
    System.out.println("Inside static initializer.");
  }

  // Constructor
  public Main() {
    System.out.println("Inside constructor.");
  }

  public static void main(String[] args) {
    System.out.println("Inside main() #1. num: " + num);

    // Declare a reference variable of the class
    Main si;

    System.out.println("Inside main() #2. num: " + num);

    // Create an object
    new Main();

    System.out.println("Inside main() #3. num: " + num);

    // Create another object
    new Main();
  }
}

Result

Related Topic