String Literal 和 String Object 的加法有什么区别?
例如
String s1 ="hello";
String s2 ="hello1";
String s3 ="hello" + "hello1";
String s4 ="hellohello1";
String s5 = s1 + s2;
System.out.println(s3 == s4); // returns true
System.out.println(s3 == s5); // return false
System.out.println(s4 == s5); // return false
为什么 s3
/s4
没有指向与 s5
相同的位置?
最佳答案
因为 s1 + s2
不是常量表达式,因为 s1
和 s2
不是 final
,因此它的结果不会被保留,即创建另一个对象来表示它,因此引用比较会产生 false
。
String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern.
JLS 15.28 Constant Expression :
A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:
- ...
- Simple names that refer to constant variables (§4.12.4).
JLS 4.12.4定义 final
变量。
如果您将 s1
和 s2
声明为 final
,则 s3 == s5
将为 true
。
关于java - 添加 String Literals 和 String 对象之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5649248/