user2210872
user2210872

Reputation: 81

Why static initializer block not run in this simple case?

 class Z
{
    static final int x=10;
    static
    {
        System.out.println("SIB");
    }

}
public class Y
{
    public static void main(String[] args)
    {
        System.out.println(Z.x);
    }
}

Output :10 why static initialization block not load in this case?? when static x call so all the static member of class z must be load at least once but static initialization block not loading.

Upvotes: 7

Views: 5537

Answers (6)

Hunter Zhao
Hunter Zhao

Reputation: 4669

The reason is that when jvm load a class, it put all the class's constant members into the constant area, when you need them, just call them directly by the class name, that is to say, it needn't to instantiate the class of Z. so the static initialization block is not executed.

Upvotes: 1

S.H.KHAN
S.H.KHAN

Reputation: 41

A constant is called perfect constant if it is declare as static final. When compiler compiling class y & while compiling sop(Z.x) it replace sop(Z.x) with sop(10) bcz x is a perfect constant that it means in byte code class Y not use class Z so while running class Y class Z is not load thats why SIB of class Z is not execute.

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

It does not run because the class is never loaded.

public class Y
{
    public static void main(String[] args)
    {
        Z z new Z(); //will load class
        System.out.println(Z.x);
    }
}

Since the x field on Z has been declared with static final they are created in a fixed memory location. Accessing this field does not require the class to be loaded.

Upvotes: 0

Parth Soni
Parth Soni

Reputation: 11658

Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class

So, when you call Z.x as below:

System.out.println(Z.x);

It won't initialize the class, except when you call that Z.x it will get that x from that fixed memory location.

Static block is runs when JVM loads class Z. Which is never get loaded here because it can access that x from directly without loading the class.

Upvotes: 1

Vallabh Patade
Vallabh Patade

Reputation: 5110

If X wouldn't have been final, in that case JVM have to load the class 'Z' and then only static block would be executed. Now JVM need not to load the 'Z' class so static block is not executed.

Upvotes: 0

AmitG
AmitG

Reputation: 10553

compile time Z.x value becomes 10, because

static final int x=10; is constant

so compiler creates code like given below, after inline

System.out.println(10); //which is not calling Z class at runtime

Upvotes: 1

Related Questions