您的位置:首页技术文章
文章详情页

请问关于 Java static 变量的问题?

【字号: 日期:2023-12-20 09:55:54浏览:90作者:猪猪

问题描述

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

标签: java
相关文章: