请问关于 Java static 变量的问题?
ringa_lee
ringa_lee 2017-04-18 10:56:42
0
2
453
public class StaticTest {

    private static String a;
    private static String b = "this is " + a;

    public static void main(String[] args) {
        a = "test";
        // I think the result is this is test
        // but the result is this is null, why?

        System.out.println(b);
    }


    //
    //  我本以为输出结果是 this is test
    // 没想到输出结果为 this is null, 这是什么原因

}
ringa_lee
ringa_lee

ringa_lee

reply all(2)
巴扎黑

First of all: when you define the A variable, you do not assign an initial value, so A is NULL, and then you get B, which is naturally this is null
Then the second one: public static void main, the compiler is compiling this code When a and b are first referenced by the main function, and you change a, a is changed, but b is still the same b, and this is null forever. You need to understand the meaning of the process of running a static function. Your B is not set dynamically, so of course what you get is the static b, and it will not be dynamically compiled.

黄舟

This is about the class initialization mechanism of JVM. The three processes of converting bytecode into running objects are loading, connection and initialization. . . The connection preparation process will give a the default value null, because StaticTest has a main method, which is set to the startup class when the JVM starts. It will perform active calls to initialize the class and execute these two lines of code private static String a; private static String b = "this is " + a;so b=this is null

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!