請問關于 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. docker網絡端口映射,沒有方便點的操作方法么?2. docker綁定了nginx端口 外部訪問不到3. thinkphp5.1學習時遇到session問題4. docker容器呢SSH為什么連不通呢?5. nignx - docker內nginx 80端口被占用6. angular.js - angular內容過長展開收起效果7. docker images顯示的鏡像過多,狗眼被亮瞎了,怎么辦?8. 前端 - ng-view不能加載進模板9. javascript - iframe 為什么加載網頁的時候滾動條這樣顯示?10. php - 第三方支付平臺在很短時間內多次異步通知,訂單多次確認收款
