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

Which will be loaded first static variable or static block?(哪个将加载第一个静态变量或静态块?)

本文介绍了哪个将加载第一个静态变量或静态块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

这篇关于哪个将加载第一个静态变量或静态块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:哪个将加载第一个静态变量或静态块?

基础教程推荐