我從 OCP O'Reilly 的 Java 書籍中學習。
有這樣一句話:
15: String first = "rat" 1;在第 15 行,我們有一個編譯時常量,它會自動作為“rat1”放入字串池中
我不明白為什么連接操作會生成編譯時常量。在我的理解中,操作應該在運行時完成。我想念的重點是什么?
uj5u.com熱心網友回復:
當在字串文字和 運算子的幫助下創建字串時,它們會在編譯時連接起來。這稱為字串的編譯時決議。
當在字串文字以及變數和 運算子的幫助下創建字串時,它們僅在運行時連接,因為變數的值無法預先預測。這稱為字串的運行時解析度。
考慮下面的例子
// Strings are computed in compile-time in this case.
public static void main(String[] args) {
String first = "rat1";
String result = "rat" 1;
System.out.println(first == result); //prints true
}
但是,在下面的代碼中,字串是在運行時計算的,因為變數one不是常量運算式:
public static void main(String[] args) {
String first = "rat1";
String one = "1";
String result = "rat" one;
System.out.println(first == result); //prints false
}
你也可以參考這個鏈接,里面有更詳細的解釋。字串的編譯時與運行時決議
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/351898.html
標籤:爪哇
