哪个将加载第一个静态变量或静态块?

2022-01-22 00:00:00 static stack core java

我的一个朋友问我哪个会加载第一个静态变量或静态块.

One of my friends asked me that which will load first static variable or static block.

我的答案指向静态变量.

My answer points to static variable.

所以他给了我两个方程,并说要区分它们
第一个方程

So he gave me two equations and said to differentiate between them
First Equation

public class Some {
    public static void main(String args[])
    {
        System.out.println(Some.x);
    }
    static {
        System.out.println(Some.x);
    }
    static int x=90;
}

O/P:0 90

O/P: 0 90

第二个方程

public class Some {
    public static void main(String args[])
    {
        System.out.println(Some.x);
    }
    static int x=90;
    static {
        System.out.println(Some.x);
    }
}

O/P:90 90

O/P: 90 90

我试图反编译字节码,发现上面两个方程都是一样的.请帮助我区分它们.当静态变量初始化时我很困惑.

I tried to decompile the byte code and found it's same for both the above equation. Please help me to differentiate between them. I am confused when the static variable will initialised.

推荐答案

静态块按照它们在源文件中出现的顺序进行初始化.关于堆栈溢出,已经有几个与此相关的问题......这个有一个很好的答案:Java : in what order静态最终字段是否已初始化?

Static blocks are initialised in the order they appear in the source file. There are several questions relating to this on stack overflow already... This one has a good answer for you: Java : in what order are static final fields initialized?

相关文章