請問關(guān)于 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); } // // 我本以為輸出結(jié)果是 this is test // 沒想到輸出結(jié)果為 this is null, 這是什么原因}
問題解答
回答1:首先第一個:你在定義A變量時,就沒有賦初值,所以A為NULL,然后得到B自然就是this is null然后第二個:public static void main,編譯器在編譯這段代碼時a,b先被main函數(shù)引用,你再更改a,a倒是被更改了,但b還是那個b,永遠(yuǎn)都是this is null。你需要明白靜態(tài)函數(shù)運行的過程的意義。你的B沒有動態(tài)被set,當(dāng)然獲得的就算那個靜態(tài)b,而不會被動態(tài)編譯。
回答2:這是關(guān)于JVM的類初始化機(jī)制吧,字節(jié)碼轉(zhuǎn)為運行對象的三個過程裝載,連接,初始化。。。其中連接的準(zhǔn)備過程會給a賦予默認(rèn)值null,因為 StaticTest 具有main方法,被設(shè)定為 JVM 啟動時的啟動類會執(zhí)行主動調(diào)用,進(jìn)行類的初始化,執(zhí)行這兩行代碼 private static String a;private static String b = 'this is ' + a;所以b=this is null
相關(guān)文章:
1. dockerfile - [docker build image失敗- npm install]2. angular.js - angular內(nèi)容過長展開收起效果3. docker-compose中volumes的問題4. 在windows下安裝docker Toolbox 啟動Docker Quickstart Terminal 失??!5. golang - 用IDE看docker源碼時的小問題6. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.7. docker內(nèi)創(chuàng)建jenkins訪問另一個容器下的服務(wù)器問題8. mac里的docker如何命令行開啟呢?9. docker容器呢SSH為什么連不通呢?10. docker-machine添加一個已有的docker主機(jī)問題

網(wǎng)公網(wǎng)安備