class test
{
test() {
System.out.println("Constructor");
}
{ System.out.println("Hai"); }
}
public class sample
{
public static void main(String [] a) {
test t = new test();
}
}
In the above code, why is "Hai" printed before the test() constructor is called?
The test() constructor in the test class is above the "Hai" statement and should be called first, right?
Let express with a more clear example:
and test it as follows:
output:
The static initializers are executed only once during runtime, specifically during loading of the class. The instance initializers are executed during every instantiation before the constructor.
You can have more than one of them and they will be executed in the order as they appear in the coding.
The major benefit of instance initializers is that they are executed regardless of which constructor you use. They applies on each of them so that you don’t need to duplicate common initialization over all of them.
The major benefit of static initializers is that they are executed only once during class loading. A well known real world example is the JDBC driver. When you do
which only executes the
staticinitializers, then any (decent) JDBC driver will register itself in theDriverManageras followsthis way the
DriverManagercan find the right JDBC driver duringgetConnection().