Initialization blocks, constructors and their order of execution

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Hello all, in this piece of article, we are going to understand what are initialization blocks and how they are executed in java programs.

Initialization blocks are places where you can perform operations like initialization of variables or execution of some statements. There are two kinds of initialization blocks

  • static initialization blocks
  • instance initialization blocks.

As their names suggest,

  • static initialization blocks are static and hence they belong to a particular class and not to the instances of class. They are defined as static { //some statements here }
  • Instance initialization blocks do not belong to a class and they are executed every time a new instance of the class is created. They are defined as {//some statements here}

There are certain rules regarding order of execution of initialization blocks and constructor. Let us list them down first and verify by writing a simple program.

  • Initialization blocks run in the order they appear in the program.
  • Static initialization blocks run when the class is first loaded into JVM
  • Instance initialization blocks run whenever a new instance of class is created.

Why should we just keep reading rules? Let us try it out using a program.

This program outputs,

Run the program using command java InitBlocksDemo. The program flows as follows

  1. When program starts executing, the class InitBlocksDemo is loaded into JVM.
  2. Static initialization blocks run when class is loaded in the order they appear in the program.
  3. Now when execution of static block completed, main method is encountered.
  4. The statement new InitBlocksDemo(); causes the no-argument constructor to be invoked.
  5.  As there is a default call to the super no-argument constructor, control goes to super class i.e.  Object  class.
  6. After it has completed, then control comes back to our class and starts giving default values to instance variables. In this case, variable name will be assigned value as null.
  7. Now the instance blocks will execute in the order they appear in the program. We have not re-assigned value to name  variable yet so it will print null
  8. After instance blocks are executed, then control goes to the constructor. Here name = "prasad"; will re-assign a new value hence “prasad” will get printed in the no-argument constructor.
  9. The statement  new InitBlocksDemo(7);  causes the one-argument constructor to be invoked. Rest of the process is same. Only difference is that name is not re-assigned a new value hence it will print null

With the help of this, we can say

  • Initialization blocks run in the order they appear in the program
  • Static initialization blocks run when class is loaded in JVM
  • Instance initialization blocks run every time a new instance is created.
  • Instance initialization blocks run AFTER the super constructor has completed executing and BEFORE current class constructor.
  • They can be used to perform operations those are common to constructors.

Hope this helps understand this concept 🙂

 

 

 

 

Share Button

Prasad Kharkar

Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

59 thoughts on “Initialization blocks, constructors and their order of execution

  • October 3, 2013 at 6:42 am
    Permalink

    This web site definitely has all the info I needed about this subject and didn’t know who to ask.

    Reply
  • October 27, 2013 at 4:57 am
    Permalink

    Hi my friend! I wish to say that this article is awesome, nice written and include approximately all vital infos. I would like to look more posts like this .

    Reply
  • November 27, 2013 at 7:45 pm
    Permalink

    Hey dude…Great web site…very useful info….You have explained very well all the concepts…Keep posting more articles 🙂

    Reply
    • November 28, 2013 at 3:39 pm
      Permalink

      Thanks Khushboo for reading. I hope the article helped you 🙂

      Reply
  • August 2, 2014 at 12:36 pm
    Permalink

    Nice explanation,,,,thanks

    Reply
  • October 17, 2014 at 1:53 am
    Permalink

    Thank you for the information. I was searching for a good explanation after an exam question in the Oracle Java exam and found this article. Very informative!

    Reply
  • November 28, 2014 at 3:00 pm
    Permalink

    very useful information.thanks 🙂

    Reply
  • January 29, 2015 at 5:27 pm
    Permalink

    is it possible to stop loading of static blocks ,static methods by default at class loading time and load after creation of object of class?

    Reply
  • March 25, 2015 at 11:00 am
    Permalink

    Hi Prasad..it is awesome..but I still have doubt that why can we declare or initialize the variables directly in constructor than using instance initialization blocks..i understand static block use as we cannot initialize static variables in a constructor..

    Reply
    • March 25, 2015 at 11:58 am
      Permalink

      Hi Shruthi, init blocks is just another way to initialize variables by java specification.

      Reply
    • February 12, 2016 at 4:20 pm
      Permalink

      Initialization blocks are common blocks of initialization. For example, if you have multiple overloaded constructors and you want to initialise some variables, you will have to write the initialisation code in all the constructors. Instead of that, you can write it once. using initialization blocks

      Reply
  • April 29, 2015 at 6:18 pm
    Permalink

    Thanks for giving nice explanation….
    But i have one doubt??
    constructor is executing first or first line i.e., private String name ; run first if i compare with in both

    Reply
  • April 30, 2015 at 9:41 am
    Permalink

    the first line runs first and then constructor runs. You can check using following program.

    public class InitBlocksDemo{

    private String name = “something”;

    {
    System.out.println(name);
    }

    InitBlocksDemo(){
    name = “prasad”;
    }

    public static void main(String [] args){
    InitBlocksDemo obj = new InitBlocksDemo();
    System.out.println(obj.name);
    }

    }

    This prints out

    something
    prasad

    Reply
  • July 8, 2015 at 3:03 pm
    Permalink

    hi Prasad…..if init block’s code runs from the constructor then is it executed after a call to super() from constructor?

    Reply
    • March 14, 2016 at 12:20 pm
      Permalink

      No , First to execute super() constructor then init block and then constructor……. 🙂

      Reply
  • September 28, 2015 at 7:21 pm
    Permalink

    Thanks a lot, nicely explained.

    Reply
  • October 24, 2015 at 3:20 pm
    Permalink

    Thank you, It was very helpful.

    Reply
  • October 24, 2015 at 3:32 pm
    Permalink

    Hi prasad, i have a small doubt.
    Super takes the control to the superclass constructor , then the control is returned to constructor of our class. How will the control go to Initialization block.Is there any inbuilt call to the Initialization block like super which calls the the super class constructor. please clarify..

    Reply
  • November 6, 2015 at 4:54 pm
    Permalink

    Why instance block is executed first in enum in compare to static block

    Reply
  • November 11, 2015 at 10:58 am
    Permalink

    how to run the second static block as first,

    public class Example{
    static
    {
    System.out.println(“first static block”);
    }
    static
    {
    System.out.println(“second static block”);
    }
    static
    {
    System.out.println(“third static block”);
    }
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    }

    }
    output:

    first static block
    second static block
    third static block

    i need :

    second static block
    first static block
    third static block

    Reply
    • December 29, 2015 at 10:19 am
      Permalink

      Priya It is not possible unless you write second static block before first static block because all the static blocks and initialization blocks get executed in order they appear.

      Reply
  • January 8, 2016 at 2:14 am
    Permalink

    Well done sir excellent…

    Reply
  • February 17, 2016 at 3:12 pm
    Permalink

    super explanation

    Reply
  • April 14, 2016 at 3:05 am
    Permalink

    I know that we can’t do it. But simply for curiosity I am asking this question that why we cant write method inside initialization block ?

    Reply
  • May 10, 2016 at 8:26 pm
    Permalink

    Nice Explanation..Thanks 🙂

    Reply
  • May 13, 2016 at 12:01 am
    Permalink

    Nice Explanation Sir ! your website is very useful for Java self learner

    Can you plz suggest me the book for java scjp or ocwcd exam..

    thanks in advance sir

    Reply
    • May 13, 2016 at 9:22 am
      Permalink

      Sun Certified Java Programmer by Kathie Sierra and Bert Bates for SCJP (OCPJP), choose the latest version though.
      Head First Servlets and JSP by Kathir Sierra, Bert Bates and Brian Basham for OCPWCD

      Reply
  • May 28, 2016 at 7:35 pm
    Permalink

    Very helpful and explained beautifully . Thanks very much

    Reply
  • June 28, 2016 at 11:40 am
    Permalink

    although it seems as if initialization of block was executed first..but constructor is invoked firstly….but what about static initialization blocks?? are they also invoked after constructor?

    Reply
  • June 28, 2016 at 9:24 pm
    Permalink

    Your explanation is great. Nice to see the stuff you provide. Great Learning Space. Thank you.

    Reply
  • July 26, 2016 at 3:51 pm
    Permalink

    how the control flow changes from constructor to main method

    Reply
    • July 26, 2016 at 4:35 pm
      Permalink

      Just like normal method execution. Constructor is called from main method. After constructor completes, it goes back to calling method. i.e. main method.

      Reply
  • August 6, 2016 at 5:45 pm
    Permalink

    how do instance initialization block executed thrice only and what is super class here we have only one class InitBlocksDemo please explain !

    Reply
    • August 8, 2016 at 9:15 am
      Permalink

      By default, every class extends Object class in java. Hence I said super class is Object.

      Reply
  • August 6, 2016 at 5:56 pm
    Permalink

    i have an question why do instance initialization block executed thrice only and what is super class we have here only one class i.e InitBlocksDemo

    Reply
    • August 8, 2016 at 9:16 am
      Permalink

      We have instantiated InitBlocksDemo three times hence instance initialization block gets executed thrice.

      Reply
  • August 6, 2016 at 5:59 pm
    Permalink

    public class InitBlocksDemo{

    private String name = “something”;

    {
    System.out.println(name);
    }

    InitBlocksDemo(){
    name = “prasad”;
    }

    public static void main(String [] args){
    InitBlocksDemo obj = new InitBlocksDemo();
    System.out.println(obj.name);
    }

    }

    this program you have given gives error as output

    Reply
  • August 8, 2016 at 1:19 pm
    Permalink

    BlocksDemo.java:3: error: illegal character: ‘\u201c’
    private String name = ?something?;
    ^
    BlocksDemo.java:3: error: illegal character: ‘\u201d’
    private String name = ?something?;
    ^
    BlocksDemo.java:10: error: illegal character: ‘\u201c’
    name = ?prasad?;
    ^
    BlocksDemo.java:10: error: illegal character: ‘\u201d’
    name = ?prasad?;
    ^
    BlocksDemo.java:10: error: not a statement
    name = ?prasad?;
    ^
    5 errors
    here are the errors

    Reply
    • August 8, 2016 at 4:04 pm
      Permalink

      some problem occurred while copying it seems, there is an illegal character coming because of some formatting issues. Please type code on your own. It should work .

      Reply
  • August 8, 2016 at 3:31 pm
    Permalink

    class InitBlocksDemo {
    String name;
    InitBlocksDemo(int x) {
    System.out.println(“In 1 argument constructor, name = ” + this.name);
    }

    InitBlocksDemo() {
    name = “prasad”;
    System.out.println(“In no argument constructor, name = ” + this.name);

    }

    /* First static initialization block */
    static {
    System.out.println(“In first static init block “);
    }

    /* First instance initialization block */
    {
    System.out.println(“In first instance init block, name = ” + this.name);
    }
    public static void main(String args[]) {
    new InitBlocksDemo();

    }}
    this is a more simpler clipped version of the above program giving output-

    In first static init block
    In first instance init block, name = null
    In no argument constructor, name = prasad

    Reply
  • August 8, 2016 at 3:41 pm
    Permalink

    it is because of the last statement
    new InitBlocksDemo(7);
    it again executing initialization block along with one argument constructor
    InitBlocksDemo();

    Reply
  • August 8, 2016 at 3:49 pm
    Permalink

    with one argument constructor
    InitBlocksDemo(int x);

    Reply
  • August 24, 2016 at 7:03 pm
    Permalink

    Hi Prasad,

    I am getting below error while executing the code mentioned by you.I just copy pasted the code and it is giving lots of error.

    Error Details are present below:
    Exception in thread “main” java.lang.Error: Unresolved compilation problems:
    Syntax error on tokens, delete these tokens
    Syntax error on tokens, delete these tokens
    Syntax error on tokens, delete these tokens
    Syntax error, insert “;” to complete Statement

    at Lab257.main(Lab257.java:36)

    Please clarify the issue.

    Thanks,
    Sumit Ranjan

    Reply
    • August 25, 2016 at 8:37 am
      Permalink

      There is nothing wrong with code. Check your class name it is Lab257.java which is different from what I have provided. Also, it seems you have copy pasted in wrong way. If you take complete program it will work.

      Reply
  • November 12, 2016 at 11:43 am
    Permalink

    Thnks for ur explaination.I am learner for java..i need help further…thanks

    Reply
  • December 15, 2016 at 10:07 pm
    Permalink

    if there are three classes,main method is in second class and every class is having a static block, then which static block gets executed first? give the sequence of execution of blocks.

    Reply
  • May 14, 2017 at 4:15 pm
    Permalink

    where we use instance initializer block in the application?

    Reply
    • May 15, 2017 at 9:51 am
      Permalink

      We generally do not use them 🙂 . This article was written to make understand the flow.

      Reply
  • January 24, 2018 at 1:29 pm
    Permalink

    Great explanation with demo

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *