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?