我怀疑我的概念在字符串池中是否清晰.请研究以下一组代码,并检查我的答案在以下一组陈述后创建的对象数量是否正确: -
1)
String s1 = "abc";
String s2 = "def";
s2 + "xyz";
Run Code Online (Sandbox Code Playgroud)
2)
String s1 = "abc";
String s2 = "def";
s2 = s2 + "xyz";
Run Code Online (Sandbox Code Playgroud)
3)
String s1 = "abc";
String s2 = "def";
String s3 = s2 + "xyz";
Run Code Online (Sandbox Code Playgroud)
4)
String s1 = "abc";
String s2 = "def";
s2 + "xyz";
String s3 = "defxyz";
Run Code Online (Sandbox Code Playgroud)
根据我所知的概念,在上面的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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
629 次 |
| 最近记录: |