Java - Order of Initialization

Subscribe Send me a message home page tags


In this post, we will take a look at the order of initialization of fields in an object.

There are four types of fields of a class and its instances:
  1. static field
  2. final static field
  3. instance field
  4. final instance field
As far as the initialization is concerned, there are four places that a field can be initialized:
  1. static initialization block
  2. object initializer block
  3. inline field initializer.
    This can be a default value or a method call.
  4. constructor

The code below contains all the concepts mentioned above and the output of the program shows the order of the initialization of each field.
public class OrderOfInitialization {

    private static int staticValue; // staticValue will be initialized in the static initialization block.
    private final static String finalStaticValue = "final static field must be initialized.";

    {
        System.out.println("Object initializer block is executed.");
        y = 20;
    }

    private int x = valueFromInitializer();
    private int y; // y will be initialized in the initializer block
    private int z; // z will be initialized in the constructor.

    static {
        System.out.println("Static initialization block is executed.");
        staticValue = 100;
    }

    public final int valueFromInitializer() {
        System.out.println("valueFromInitializer() is called.");
        return 10;
    }

    public OrderOfInitialization() {
        System.out.println("Constructor() is called.");
        System.out.println("(uninitialized) z = " + z);
        z = 30;
        System.out.println("(initialized in constructor) z = " + z);

        System.out.println("staticValue = " + staticValue);
        System.out.println("finalStaticValue = " + finalStaticValue);
    }

    public static void main(String[] args) {
        OrderOfInitialization instance = new OrderOfInitialization();
    }
}

Here is the output of the program:
Static initialization block is executed.
Object initializer block is executed.
valueFromInitializer() is called.
Constructor() is called.
(uninitialized) z = 0
(initialized in constructor) z = 30
staticValue = 100
finalStaticValue = final static field must be initialized.

----- END -----

If you have questions about this post, you could find me on Discord.
Send me a message Subscribe to blog updates

Want some fun stuff?

/static/shopping_demo.png