根據JLS(15.28常量表達式)僅包含一個表達式:運行時字符串連接評價
i)Literals of primitive type and literals of type String (§3.10.1, §3.10.2, §3.10.3,
§3.10.4, §3.10.5)
or
ii)Simple names (§6.5.6.1) that refer to constant variables (§4.12.4).
or
iii)...
是一個常量表達式。
現在String s1="a"+"b";
爲常量表達式與在編譯時將被評估,以"ab"
。
所以s1="ab";
[1] 我是正確地說,現在有在字符串池三個對象爲根據上面的語句: - 「A」, 「B」, 「AB」 ???
現在,
final String s="a";
final String s1="b";
String s2=s+s1; // is also constant expression and get evaluated at compile time.
上面的代碼將編譯後transaled到s2="a"+"b";
。
所以s2="ab";
將被自動保存在字符串池。
但是,
// note there is no final now.
String s="a";
String s1="b";
String s2="a"+"b"; // constant expression.
String s3=s+s1; // is NOT a constant expression and get evaluated at RUN TIME.
爲String s3=s+s1;
,代碼將被翻譯成:
s3=new StringBuilder(String.valueOf(s)).append(s1).toString();
,將創建一個新的String對象。
因此,s2==s3
將出來是假的;
這是否意味着在運行時使用StringBuilder求值的字符串連接的結果不是存儲在字符串池中,而是進入堆(池外)?
請注意,編譯階段的字符串池與運行程序時的字符串池不同。 –
@ThorbjørnRavn Andersen:尼斯點。你可以給我任何鏈接或來源,我可以看到你的觀點的細節。 –