Initialization Blocks : variable scope « Java Source And Data Type « SCJP






Init blocks execute in the order they appear.
Static init blocks run once, when the class is first loaded.
Instance init blocks run every time a class instance is created.
Instance init blocks run after the constructor's call to super().

class SmallInit {
  static int x;

  int y;

  static {
    x = 7;
  } // static init block
  {
    y = 8;
  } // instance init block
}

class Init {
  Init(int x) {
    System.out.println("1-arg const");
  }

  Init() {
    System.out.println("no-arg const");
  }

  static {
    System.out.println("1st static init");
  }
  {
    System.out.println("1st instance init");
  }
  {
    System.out.println("2nd instance init");
  }
  static {
    System.out.println("2nd static init");
  }

  public static void main(String[] args) {
    new Init();
    new Init(7);
  }
}
1st static init
2nd static init
1st instance init
2nd instance init
no-arg const
1st instance init
2nd instance init
1-arg const








1.26.variable scope
1.26.1.Variable Scope
1.26.2.Attempting to access an instance variable from a static context.
1.26.3.Attempting to access a local variable from a nested method.
1.26.4.Attempting to use a block variable after the code block has completed.
1.26.5.Primitive and Object Type Instance Variables
1.26.6.Initialization Blocks