7
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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
UnderDog
  • 3,173
  • 10
  • 32
  • 49

4 Answers4

36

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.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
9

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.

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
6

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

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
jmj
  • 237,923
  • 42
  • 401
  • 438
0

Static block one time execution block.. it executes while class loading..

when object is created for a class constructor executes..

sasi
  • 4,192
  • 4
  • 28
  • 47