class prog
{
static
{
System.out.println("s1");
}
prog()
{
System.out.println("s2");
}
public static void main(String...args)
{
prog p = new prog();
}
}
Output is
s1
s2
As per the output, it seems that static initialization block gets executed before the default constructor itself is executed.
What is the rationale behind this?
Static block
executed once at the time of class-loading & initialisation by JVM and constructor is called at the every time of creating instance of that class.
If you change your code -
public static void main(String...args){
prog p = new prog();
prog p = new prog();
}
you'll get output -
s1 // static block execution on class loading time
s2 // 1st Object constructor
s2 // 2nd object constructor
Which clarifies more.
Strictly speaking, static initializers are executed, when the class is initialized.
Class loading is a separate step, that happens slightly earlier. Usually a class is loaded and then immediately initialized, so the timing doesn't really matter most of the time. But it is possible to load a class without initializing it (for example by using the three-argument Class.forName()
variant).
No matter which way you approach it: a class will always be fully initialized at the time you create an instance of it, so the static
block will already have been run at that time.
That is right static initialization is being done when class is loaded by class loader and constructor when new instance is created
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With