1

The title may not be easy to understand but basically I have seen this in some programs and I am curious about it , to clear things out I have simplified the code to the extent where we can concentrate on my question.

public class A {

    public A() {
        System.out.println("constructor");
    }
    static{
        System.out.println("static");
    }
}

-

public class B {

    public static void main(String[] args) {

        A a = new A();
    }

}

when I run the code the output is:

static

constructor

what exactly is this static with brackets? from the looks of it seems like it runs the code inside the brackets when the class is used but why exist if we have the constructor? Can't we put the code we need to initialize inside the constructor? and it seems to run its code before the constructor since the word static comes before the word constructor, why is that so?

Simulant
  • 19,190
  • 8
  • 63
  • 98
securenova
  • 482
  • 1
  • 9
  • 25
  • It's called a static initializer, it runs when you run the app. You don't even need an instance of A for it. It's the same scope as what creates the ENUM instances for you (it runs after that). – EpicPandaForce Mar 30 '16 at 16:31

1 Answers1

0

It is static initialization block, check it here

public class Test{
    public Test(){
        // constructor initialization
    }

    static{
        // static initializer
    }

    {
        // instance initializer
    }

}

The initialization order is static initializer, instance initializer, constructor initializer.

Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125