Init Block

<< Previous Chapter Next Chapter >>
Init Block In Java:

The block without name is known as init block. In simple word any opening and closing curly braces '{}' with few statements is known as init block.

Example:
class Student {
      {
            System.out.println("Init Block");
      }

      Student() {
            System.out.println("default");
      }

      Student(int x) {
            System.out.println(x);
      }

      public static void main(String args[]) {
            new Student();
            new Student(10);
            new Student();
      }
}

Output:

Init Block
default
Init Block
10
Init Block
default

Init block gets executed automatically before constructor.

Rule1:
Init block is executed before any constructor whenever that constructor is used for making a new object.

Rule2:
We can have more than one init block in a class. All will be executed in order they are defined, and get executed before constructor. Init block can use any non static data members.

Now, question arise that how “this” keyword is reached in init block automatically?
So, the answer is, all statements of init block is implicitly inserted into every constructor of the same class as a first line. The reason why we prefer init block is that, when we want to perform common tasks in all constructors like database connections on creation of each object, so it is not 100% sure that programmer will call all constructors. So, if we will put those types of common tasks in init block then it will definitely be executed.


Example: let’s take a simple example to just print a message “Welcome world!” in each constructor call:

class Temp
{
      {
            System.out.println("Welcome World!");
      }

      Temp()
      {
            System.out.println("Default constructor executed.");
      }
      Temp(int x)
      {
            System.out.println("Parameterized constructor executed.");
      }
      public static void main(String args[])
      {
            Temp t1 = new Temp();
            Temp t2 = new Temp(20);
      }
     
}

Output:

1 comment: