请问关于 Java static 变量的问题?
问题描述
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, 这是什么原因}
问题解答
回答1:首先第一个:你在定义A变量时,就没有赋初值,所以A为NULL,然后得到B自然就是this is null然后第二个:public static void main,编译器在编译这段代码时a,b先被main函数引用,你再更改a,a倒是被更改了,但b还是那个b,永远都是this is null。你需要明白静态函数运行的过程的意义。你的B没有动态被set,当然获得的就算那个静态b,而不会被动态编译。
回答2:这是关于JVM的类初始化机制吧,字节码转为运行对象的三个过程装载,连接,初始化。。。其中连接的准备过程会给a赋予默认值null,因为 StaticTest 具有main方法,被设定为 JVM 启动时的启动类会执行主动调用,进行类的初始化,执行这两行代码 private static String a;private static String b = 'this is ' + a;所以b=this is null
相关文章:
1. Mysql取下一条记录2. 求助一个Android控件名称3. javascript 如何下载一个excel文件 ?4. notepad+编写的html,打开就是这样了。为什么,大神们5. Chrome-org.openqa.selenium.WebDriverException:未知错误:无法在driver.manage()window()maximize();处获得自动化扩展6. mysql federated引擎无法开启7. python 如何打印bytes以16进制输出8. javascript - vue-resource 如何二次封装9. sublime text 3不支持python的input吗10. python对8000行csv添加列

网公网安备