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
//Instance Initialisation Block

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);

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 replies »

  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.


  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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.