Site icon Experiences Unlimited

Initialisation Blocks in Java

Topic: Initialisation Blocks in Java

Apart from methods and constructors, initialisation blocks are the places where operations within a class can be performed.

Initialisations blocks can be:

Static Initialisation blocks run only once when the class is first loaded.

Instance Initialisation blocks run each time when the instance of the class is created.

Code Example:

class InitBlocks
{
static int a;
int b;
// Static initialisation block
static
{
a=4;
}
//Instance Initialisation Block
{
b=10;
}
}

Instance init block code runs right after the call to super() in a constructor, in other words after all the super consructors have run.

When its time for initialisation blocks to run, if a class has more than one, they will run in the order in which they appear in the class file i.e from the top-down.

Some rules to be remembered with regards to Initialisation Blocks:

Rule 1: Initialisation Blocks execute in the order they appear.
Rule 2: Static Initialisation Blocks run once, when the class is first loaded.
Rule 3: Instance Initialisation Blocks run after the constructor’s call to super().
Rule 4: Instance Initialisation Blocks run every time a class instance is created.

Code Example:

class InitBlock
{
InitBlock(int x){System.out.println(“1 Arg Constructor”);}

InitBlock(){System.out.println(“0 Arg Constructor”);}

static{System.out.println(“1st Static Init Block”);}
{System.out.println(“1st Instance Init Block”);}
{System.out.println(“2nd Instance Init Block”);}
static{System.out.println(“2nd Static Init Block”);}

public static void main(String[] args)
{
new InitBlock();
new InitBlock(2);
}
}

Output:
1st Static Init Block
2nd Static Init Block
1st Instance Init Block
2nd Instance Init Block
0 Arg Constructor
1st Instance Init Block
2nd Instance Init Block
1 Arg Constructor

Source: SCJP Study Guide, Kathy Sierra and Bert Bates (Exam 310-055)

Exit mobile version