Using Initialization Blocks: static initialization block : Initialization Block « Class Definition « Java Tutorial






  1. A block defined using the keyword static.
  2. Executed once when the class is loaded.
  3. Can initialize only static data members of the class.
public class MainClass {
  static int[] values = new int[10];

  static {
    System.out.println("Running initialization block.");
    for (int i = 0; i < values.length; i++) {
      values[i] = (int) (100.0 * Math.random());
    }
  }

  void listValues() {
    for (int value : values) {
      System.out.println(value);
    }
  }

  public static void main(String[] args) {
    MainClass example = new MainClass();
    System.out.println("\nFirst object:");
    example.listValues();

    example = new MainClass();
    System.out.println("\nSecond object:");
    example.listValues();
  }
}
Running initialization block.

First object:
58
22
49
75
1
35
76
19
27
63

Second object:
58
22
49
75
1
35
76
19
27
63








5.11.Initialization Block
5.11.1.A class that contains a static initializer:
5.11.2.Initializing Data Members
5.11.3.Initialization order
5.11.4.Using Initialization Blocks: A non-static initialization block
5.11.5.Using Initialization Blocks: static initialization block
5.11.6.Mixed Initializer
5.11.7.Explicit static initialization with the static clause
5.11.8.The full process of initialization
5.11.9.Demonstrates various initializers
5.11.10.Demonstrates the pitfalls of depending on the order of static initializers