Mixed Initializer : Initialization Block « Class Definition « Java Tutorial






public class MixedInitializer {
  int i1;
  static int i2;
  int i3 = 2;
  static int i4 = 4;
  {
    System.out.println("i1 = " + i1);
    i1 = 6;
    System.out.println("i1 = 6");
  }
  static {
    System.out.println("i2 = " + i2);

    i2 = 8;

    System.out.println("i2 = 8");
  }

  public static void main(String[] args) {
    System.out.println("main() entered");
    MixedInitializer mi = new MixedInitializer();
    System.out.println("mi.i1 = " + mi.i1);
    System.out.println("i2 = " + i2);
    System.out.println("mi.i3 = " + mi.i3);
    System.out.println("i4 = " + i4);

    System.out.println("main() exited");
  }

  {
    i1 += 6;
    System.out.println("6 + i1");
  }

  static {
    i2 -= 3;
    System.out.println("i2 -= 3");
  }
}








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