Why static initializer block not run in this simple case?

☆樱花仙子☆ 提交于 2019-12-10 04:37:18

问题


 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.


回答1:


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.




回答2:


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



回答3:


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.




回答4:


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.




回答5:


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.




回答6:


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.



来源:https://stackoverflow.com/questions/15633536/why-static-initializer-block-not-run-in-this-simple-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!