6
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
  • 34,719
  • 24
  • 185
  • 251
UnderDog
  • 3,003
  • 10
  • 30
  • 47

4 Answers4

35

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
  • 39,719
  • 12
  • 74
  • 101
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
  • 291,719
  • 55
  • 540
  • 600
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
  • 118,038
  • 37
  • 189
  • 297
jmj
  • 232,312
  • 42
  • 391
  • 431
0

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

when object is created for a class constructor executes..

sasi
  • 3,886
  • 4
  • 26
  • 47