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
  • Instance

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)

3 thoughts on “Initialisation Blocks in Java”

  1. @freeall-
    JNI’s use static blocks to load the library. U can do operations which have to be done immediately after loading the class and before creating any instances in the Static Initialization blocks.

    Reply
  2. @freeall: Instance initialization blocks are inserted into every constructor, so you can have multiple constructors that share some behavior but customise other things. Also, using an unnamed block means you don’t mistype method names.

    Reply

Leave a Reply

Discover more from Experiences Unlimited

Subscribe now to keep reading and get access to the full archive.

Continue reading