2011-08-22 137 views
4

我懷疑我的概念在stringpool中是否清楚。請仔細閱讀下面的一組代碼,並檢查我的答案在下面一組語句之後創建的對象的數量是正確的: -Java字符串池對象創建

1)

String s1 = "abc"; 
String s2 = "def"; 
s2 + "xyz"; 

2)

String s1 = "abc"; 
String s2 = "def"; 
s2 = s2 + "xyz"; 

3 )

String s1 = "abc"; 
String s2 = "def"; 
String s3 = s2 + "xyz"; 

4)

String s1 = "abc"; 
String s2 = "def"; 
s2 + "xyz"; 
String s3 = "defxyz"; 

根據我所知道的概念,在上述所有4種情況下,在執行每組行後都會創建4個對象。

+0

告訴我們爲什麼,例如,爲什麼有3個爲什麼有4個對象。 – djna

+0

在前三個中,每個只有3個字符串對象... –

+0

@djna:是的。編譯器可以自由使用三個對象,因爲s2 +「xyz」可以在編譯時進行評估。 – Thilo

回答

7

你不能像s2 + "xyz"自己的表達。只有常量由編譯器評估,只有字符串常量會自動添加到字符串文字池中。

例如

final String s1 = "abc"; // string literal 
String s2 = "abc"; // same string literal 

String s3 = s1 + "xyz"; // constants evaluated by the compiler 
         // and turned into "abcxyz" 

String s4 = s2 + "xyz"; // s2 is not a constant and this will 
         // be evaluated at runtime. not in the literal pool. 
assert s1 == s2; 
assert s3 != s4; // different strings. 
1

你爲什麼在意?其中一些取決於編譯器優化的積極性,所以沒有真正的正確答案。