Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static initialization block vs constructor java [duplicate]

Tags:

java

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?

like image 601
UnderDog Avatar asked Sep 04 '13 05:09

UnderDog


3 Answers

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.

like image 145
Subhrajyoti Majumder Avatar answered Nov 17 '22 04:11

Subhrajyoti Majumder


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.

like image 31
Joachim Sauer Avatar answered Nov 17 '22 03:11

Joachim Sauer


That is right static initialization is being done when class is loaded by class loader and constructor when new instance is created

like image 6
jmj Avatar answered Nov 17 '22 03:11

jmj