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.

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

58 comments for “Initialization blocks, constructors and their order of execution

  1. October 3, 2013 at 6:42 am

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

  2. October 27, 2013 at 4:57 am

    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 .

  3. November 1, 2013 at 11:32 pm

    Hey very nice TEXT!

  4. Khushboo
    November 27, 2013 at 7:45 pm

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

    • Prasad Kharkar
      November 28, 2013 at 3:39 pm

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

  5. Priyadharshini
    August 2, 2014 at 12:36 pm

    Nice explanation,,,,thanks

    • August 2, 2014 at 12:51 pm

      Hi Priyadarshini. I am glad you found it useful. Happy learning 🙂

  6. September 9, 2014 at 11:53 am

    Nice explanation and thank you.it is very helpfull

    • September 10, 2014 at 9:51 am

      I am glad it was useful 🙂 Happy learning.

  7. Maaike
    October 17, 2014 at 1:53 am

    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!

    • October 17, 2014 at 10:15 am

      Hi Maaike, I am glad this was useful 🙂 Happy learning.

  8. pavitra
    November 28, 2014 at 3:00 pm

    very useful information.thanks 🙂

  9. venky
    January 29, 2015 at 5:27 pm

    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?

    • January 30, 2015 at 2:39 pm

      that will break the purpose of static blocks. It is not possible.

  10. shruthi
    March 25, 2015 at 11:00 am

    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..

    • March 25, 2015 at 11:58 am

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

    • Dhruv
      February 12, 2016 at 4:20 pm

      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

  11. Ravi Singh
    April 29, 2015 at 6:18 pm

    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

  12. April 30, 2015 at 9:41 am

    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

    • Ranjeet
      May 20, 2016 at 1:14 pm

      something

  13. Aakash
    July 8, 2015 at 3:03 pm

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

    • Milind
      March 14, 2016 at 12:20 pm

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

  14. Deep
    September 28, 2015 at 7:21 pm

    Thanks a lot, nicely explained.

  15. Vilas
    October 24, 2015 at 3:20 pm

    Thank you, It was very helpful.

  16. Vilas
    October 24, 2015 at 3:32 pm

    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..

  17. kailash
    November 6, 2015 at 4:54 pm

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

  18. priya
    November 11, 2015 at 10:58 am

    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

    • Ganesh
      December 29, 2015 at 10:19 am

      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.

  19. Raj Roushan
    January 8, 2016 at 2:14 am

    Well done sir excellent…

  20. RammohnReddy
    February 17, 2016 at 3:12 pm

    super explanation

  21. Roshan
    April 14, 2016 at 3:05 am

    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 ?

  22. Karthik Rajesh Ponnuchamy
    May 10, 2016 at 8:26 pm

    Nice Explanation..Thanks 🙂

  23. Deepak tailor
    May 13, 2016 at 12:01 am

    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

    • May 13, 2016 at 9:22 am

      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

  24. May 28, 2016 at 7:35 pm

    Very helpful and explained beautifully . Thanks very much

  25. Shivam
    June 28, 2016 at 11:40 am

    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?

  26. Sanketh
    June 28, 2016 at 9:24 pm

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

  27. Dinesh
    July 26, 2016 at 3:51 pm

    how the control flow changes from constructor to main method

    • July 26, 2016 at 4:35 pm

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

  28. anuj
    August 6, 2016 at 5:45 pm

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

    • August 8, 2016 at 9:15 am

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

  29. anuj
    August 6, 2016 at 5:56 pm

    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

    • August 8, 2016 at 9:16 am

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

  30. anuj
    August 6, 2016 at 5:59 pm

    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

    • August 8, 2016 at 9:17 am

      Please post the error you are getting, I will be glad to help you out.

  31. anuj
    August 8, 2016 at 1:19 pm

    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

    • August 8, 2016 at 4:04 pm

      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 .

  32. anuj
    August 8, 2016 at 3:31 pm

    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

  33. anuj
    August 8, 2016 at 3:41 pm

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

  34. anuj
    August 8, 2016 at 3:49 pm

    with one argument constructor
    InitBlocksDemo(int x);

  35. sumit ranjan
    August 24, 2016 at 7:03 pm

    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

    • August 25, 2016 at 8:37 am

      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.

  36. sandeep
    November 12, 2016 at 11:43 am

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

  37. priyanka
    December 15, 2016 at 10:07 pm

    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.

  38. January 21, 2017 at 4:37 pm

    well said about Initialization blocks, constructors and their order of execution..java training in chennai

  39. gagan deep
    May 14, 2017 at 4:15 pm

    where we use instance initializer block in the application?

    • May 15, 2017 at 9:51 am

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

  40. Surya Aniketh
    July 7, 2017 at 3:43 pm

    Excellent

Leave a Reply

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