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个对象。

你不能拥有像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. 

你为什么在乎? 其中一些取决于编译器优化的积极程度,因此没有实际的正确答案。