2011-08-22 145 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

你为什么在意?其中一些取决于编译器优化的积极性,所以没有真正的正确答案。