What is an initialization block?

75,582

Solution 1

First of all, there are two types of initialization blocks:

  • instance initialization blocks, and
  • static initialization blocks.

This code should illustrate the use of them and in which order they are executed:

public class Test {

    static int staticVariable;
    int nonStaticVariable;        

    // Static initialization block:
    // Runs once (when the class is initialized)
    static {
        System.out.println("Static initalization.");
        staticVariable = 5;
    }

    // Instance initialization block:
    // Runs each time you instantiate an object
    {
        System.out.println("Instance initialization.");
        nonStaticVariable = 7;
    }

    public Test() {
        System.out.println("Constructor.");
    }

    public static void main(String[] args) {
        new Test();
        new Test();
    }
}

Prints:

Static initalization.
Instance initialization.
Constructor.
Instance initialization.
Constructor.

Instance itialization blocks are useful if you want to have some code run regardless of which constructor is used or if you want to do some instance initialization for anonymous classes.

Solution 2

would like to add to @aioobe's answer

Order of execution:

  1. static initialization blocks of super classes

  2. static initialization blocks of the class

  3. instance initialization blocks of super classes

  4. constructors of super classes

  5. instance initialization blocks of the class

  6. constructor of the class.

A couple of additional points to keep in mind (point 1 is reiteration of @aioobe's answer):

  1. The code in static initialization block will be executed at class load time (and yes, that means only once per class load), before any instances of the class are constructed and before any static methods are called.

  2. The instance initialization block is actually copied by the Java compiler into every constructor the class has. So every time the code in instance initialization block is executed exactly before the code in constructor.

Solution 3

nice answer by aioobe adding few more points

public class StaticTest extends parent {
    static {
        System.out.println("inside satic block");
    }

    StaticTest() {
        System.out.println("inside constructor of child");
    }

    {
        System.out.println("inside initialization block");
    }

    public static void main(String[] args) {
        new StaticTest();
        new StaticTest();
        System.out.println("inside main");
    }
}

class parent {
    static {
        System.out.println("inside parent Static block");
    }
    {
        System.out.println("inside parent initialisation block");
    }

    parent() {
        System.out.println("inside parent constructor");
    }
}

this gives

inside parent Static block
inside satic block
inside parent initialisation block
inside parent constructor
inside initialization block
inside constructor of child
inside parent initialisation block
inside parent constructor
inside initialization block
inside constructor of child
inside main

its like stating the obvious but seems a little more clear.

Solution 4

The sample code, which is approved as an answer here is correct, but I disagree with it. It does not shows what is happening and I'm going to show you a good example to understand how actually the JVM works:

package test;

    class A {
        A() {
            print();
        }

        void print() {
            System.out.println("A");
        }
    }

    class B extends A {
        static int staticVariable2 = 123456;
        static int staticVariable;

        static
        {
            System.out.println(staticVariable2);
            System.out.println("Static Initialization block");
            staticVariable = Math.round(3.5f);
        }

        int instanceVariable;

        {
            System.out.println("Initialization block");
            instanceVariable = Math.round(3.5f);
            staticVariable = Math.round(3.5f);
        }

        B() {
            System.out.println("Constructor");
        }

        public static void main(String[] args) {
            A a = new B();
            a.print();
            System.out.println("main");
        }

        void print() {
            System.out.println(instanceVariable);
        }

        static void somethingElse() {
            System.out.println("Static method");
        }
    }

Before to start commenting on the source code, I'll give you a short explanation of static variables of a class:

First thing is that they are called class variables, they belong to the class not to particular instance of the class. All instances of the class share this static(class) variable. Each and every variable has a default value, depending on primitive or reference type. Another thing is when you reassign the static variable in some of the members of the class (initialization blocks, constructors, methods, properties) and doing so you are changing the value of the static variable not for particular instance, you are changing it for all instances. To conclude static part I will say that the static variables of a class are created not when you instantiate for first time the class, they are created when you define your class, they exist in JVM without the need of any instances. Therefor the correct access of static members from external class (class in which they are not defined) is by using the class name following by dot and then the static member, which you want to access (template: <CLASS_NAME>.<STATIC_VARIABLE_NAME>).

Now let's look at the code above:

The entry point is the main method - there are just three lines of code. I want to refer to the example which is currently approved. According to it the first thing which must be printed after printing "Static Initialization block" is "Initialization block" and here is my disagreement, the non-static initialization block is not called before the constructor, it is called before any initializations of the constructors of the class in which the initialization block is defined. The constructor of the class is the first thing involved when you create an object (instance of the class) and then when you enter the constructor the first part called is either implicit (default) super constructor or explicit super constructor or explicit call to another overloaded constructor (but at some point if there is a chain of overloaded constructors, the last one calls a super constructor, implicitly or explicitly).

There is polymorphic creation of an object, but before to enter the class B and its main method, the JVM initializes all class(static) variables, then goes through the static initialization blocks if any exist and then enters the class B and starts with the execution of the main method. It goes to the constructor of class B then immediately (implicitly) calls constructor of class A, using polymorphism the method(overridden method) called in the body of the constructor of class A is the one which is defined in class B and in this case the variable named instanceVariable is used before reinitialization. After closing the constructor of class B the thread is returned to constructor of class B but it goes first to the non-static initialization block before printing "Constructor". For better understanding debug it with some IDE, I prefer Eclipse.

Solution 5

Initializer block contains the code that is always executed whenever an instance is created. It is used to declare/initialise the common part of various constructors of a class.

The order of initialization constructors and initializer block doesn’t matter, initializer block is always executed before constructor.

What if we want to execute some code once for all objects of a class?

We use Static Block in Java.

Share:
75,582
Sumithra
Author by

Sumithra

I am a beginner learning JAVA.

Updated on July 10, 2022

Comments

  • Sumithra
    Sumithra almost 2 years

    We can put code in a constructor or a method or an initialization block. What is the use of initialization block? Is it necessary that every java program must have it?

  • Nicolas Barbulesco
    Nicolas Barbulesco almost 10 years
    According to @Biman, the constructors from superclasses are run before the init block.
  • arkon
    arkon over 9 years
    TL;DR OP simply asked for an explanation of the initialization block, not a long-winded explanation on the fundamentals of static variables, constructors, or your IDE preferences.
  • Thomas Weller
    Thomas Weller over 9 years
    Even if you interpreted the question as "How do I initialise my instance variables?", your answer does not mention that it can be done with initializers.
  • Thomas Weller
    Thomas Weller over 9 years
    At the moment it looks like they are executed in order of appearance in the code. The example could be improved in the way the order in code is different to the actual execution order. Also: there can be several initialization blocks and then they are executed in order of appearance (but still before the constructor).
  • pablisco
    pablisco over 7 years
    @Pacerier So you can have common code when having multiple constructors without having to use an init() method (which someone updating the class may forget to call it)
  • user7610
    user7610 about 7 years
    Sometimes, these longwinded explanations can get unexpectedly popular. Either if those asking the original question really need a longwinded explanation to get their foundations straight. Or if people read the answer by itself, as if it was a blog on a given topic. In this instance, it is neither, I'd say.
  • Glen Pierce
    Glen Pierce about 7 years
    So if I create 10 instances of SomeClass, steps 1 and 2 only get performed once, until something causes the class to get unloaded (only thing I can think of is restarting the program, but if there are other things that can cause that, I'd like to know).
  • Glen Pierce
    Glen Pierce about 7 years
    @nenito, I think that your comment on the accepted answer is misleading. I encourage you to rephrase it to something more like "I have a more nuanced explanation that may be of interest." The accepted answer does seem to be exactly correct, simply not as detailed as yours.
  • Biman Tripathy
    Biman Tripathy about 7 years
  • nenito
    nenito about 7 years
    @Glen Pierce: The accepted answer was modified after my comment. My sentence gives not only the answer but also some additional info which I think is useful for junior and intermediate level Java developers.
  • amarnath harish
    amarnath harish almost 6 years
    @Thomas wellerif its executes before constructor how come it allows this keyword inisde instance initialize block . this is curernt class object and it will constructed fully after the constructor call finishes right?
  • ceving
    ceving over 3 years
    Will a child class inherit the instance initialization block?
  • Biman Tripathy
    Biman Tripathy over 3 years
    No, inheritance does not apply to initialization blocks
  • Prasanna
    Prasanna over 3 years
    The instance initialization block is actually copied by the Java compiler into every constructor the class has - this is not always true. It will not be copied if the constructor explicitily invokes another constructor.
  • torez233
    torez233 over 2 years
    @Prasanna is it because if a constructor is explicitly invoked within another constructor, it has to be the first statement ?