Friday, March 7, 2014

Block, Static Block and Constructor Execution

One of the most basic question in core java that we encounter in interviews is related to blocks/static blocks.

I am sharing a problem that will clear the basic concepts on How Blocks and Static Blocks Work in Java ?

Sample code displaying block, static block and constructor execution. 
Yes, we can define blocks like -

{
       System.out.println("Starting block....");
}


Note: It does not give any compile time error.

As we can see in the screenshot the order of execution of blocks and constructor in Java is -

  1. Static block is the first block that gets loaded.
  2. Then any other blocks as defined
  3. Constructor is last to be loaded

No comments:

Post a Comment