Thursday, June 7, 2012

Initialization block in java class


The initialization block is one of the elements of java class. It is a block of code between braces. When you create any object of that class the initialization block is the first executable block. So if you want to put some code which has to be executing before object initialization, you can make use of initialization block.

There are two types of Initialization block, instance initialization block and static initialization block


Instance initialization block

The instance initialization block is the simple block between braces. You can put any code that's you want be execute before creating the Object of class. The example of instance initialization block given below.


class A {
{
System.out.println("Inside instance initialization block");
}
}
Static initialization block

The static initialization block is the simple block between braces but the before first brace you have to put static keyword as given in below example. You can put any code that's you want be execute before loading the class in memory. The example of static initialization block given below.


class A {
static {
System.out.println("Inside static initialization block");
}
}

The difference between instance and static initialization block is not only the static keyword. As the instance initialization block will be execute before the instance of that object created, and the static initialization block will be execute before the class loaded into the memory as the static keyword itself is for class level.

You can have as many initialization blocks in java class as you want. In this case they execute in the sequence from top to bottom.

There can be one question in your mind that why we need constructor when we have initialization blocks. The answer is initialization blocks cannot be parameterized.

No comments:

Post a Comment