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, 这是什么原因
}
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