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

2023-09-07 10:03:18 作者:忆相逢

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

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?