Java - Instance Initialization Block

What is Instance Initialization Block?

An instance initialization block is used to initialize objects of a class.

Syntax

An instance initializer is a block of code inside the body of a class, but outside any methods or constructors.

An instance initializer does not have a name.

Its code is placed inside an opening brace and a closing brace.

Rule

An instance initializer cannot have a return statement.

Example

The following code shows how to declare an instance initializer.

class Test {
  private int num;

  // An instance initializer
  {
    this.num = 101;
  }
}

Multiple instance initializers

Code for all instance initializers are executed before any constructor.

The following code demonstrates the sequence in which the constructor and instance initializers are executed.

Demo

class Main {
  {//from  w w w  .  ja  v  a 2 s. c  o m
    System.out.println("Inside instance initializer 1.");
  }

  {
    System.out.println("Inside instance initializer 2.");
  }

  public Main() {
    System.out.println("Inside no-args constructor.");
  }

  public static void main(String[] args) {
    Main m = new Main();
  }
}

Result

Related Topics