Why static initializer block not run in this simpl

2019-04-28 10:12发布

 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.

6条回答
\"骚年 ilove
2楼-- · 2019-04-28 10:32

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.

查看更多
祖国的老花朵
3楼-- · 2019-04-28 10:35

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.

查看更多
来,给爷笑一个
4楼-- · 2019-04-28 10:41

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.

查看更多
我命由我不由天
5楼-- · 2019-04-28 10:41

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.

查看更多
该账号已被封号
6楼-- · 2019-04-28 10:52

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
查看更多
小情绪 Triste *
7楼-- · 2019-04-28 10:54

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.

查看更多
登录 后发表回答