Static Initializers vs Instance Initializers vs Constructors

steven0529 picture steven0529 · Feb 21, 2014 · Viewed 8.2k times · Source

I am studying for an exam about Java. While I was studying, I have encountered syntaxes in java which are unfamiliar to me. Such as a curly braces({}) unside a class body without a name, some has a static keyword. I have found out that they are called "Initializers". Can anyone help me point out key differences among them and how they differ from a Constructor. Thanks

Answer

Trein picture Trein · Feb 21, 2014

The main difference between them is the order they are executed. To illustrate, I will explain them with an example:

public class SomeTest {

    static int staticVariable;
    int instanceVariable;        

    // Static initialization block:
    static {
        System.out.println("Static initialization.");
        staticVariable = 5;
    }

    // Instance initialization block:
    {
        System.out.println("Instance initialization.");
        instanceVariable = 10;
    }

    // Constructor
    public SomeTest() {
        System.out.println("Constructor executed.");
    }

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

The output will be:

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

Briefly talking:

  • Static initialization blocks run once the class is loaded by the JVM.
  • Instance initialization blocks run before the constructor each time you instantiate an object.
  • Constructor (obviously) run each time you instantiate an object.