Roman Roman - 1 year ago 74
Java Question

Static Initialization Blocks

As far as I understood the "static initialization block" is used to set values of static field if it cannot be done in one line.

But I do not understand why we need a special block for that. For example we declare a field as static (without a value assignment). And then write several lines of the code which generate and assign a value to the above declared static field.

Why do we need this lines in a special block like:

static {...}

Answer Source

The non-static block:

    // Do Something...

Gets called every time an instance of the class is constructed. The static block only gets called once, when the class itself is initialized, no matter how many objects of that type you create.


public class Test {


        System.out.println("Non-static block");

    public static void main(String[] args) {
        Test t = new Test();
        Test t2 = new Test();

This prints:

Non-static block
Non-static block