字符串文字和字符串对象之间的区别 [英] Difference between addition of String Literals and String objects
问题描述
添加字符串文字和字符串对象有什么区别?
What is the difference between an addition of String Literal and 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
相同的位置?
Why do s3
/s4
not point to the same location as s5
?
推荐答案
由于s1 + s2
不是常量表达式,因为s1
和s2
不是final
,因此其结果没有被求和,即创建了另一个对象来表示它,因此引用比较会生成false
.
Because s1 + s2
is not a constant expression, since s1
and s2
are not final
, therefore its result is not interned, i.e. another object is created to represent it, so reference comparison produces false
.
使用String.intern方法对字符串文字(或更一般地说,是常量表达式的值(第15.28节)的字符串)进行插入",以便共享唯一的实例.
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.
编译时常量表达式是表示原始类型或String的值的表达式,该值不会突然完成,并且仅使用以下内容组成:
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:
- ...
- 引用常量变量的简单名称(第4.12.4节).
JLS 4.12.4 定义了final
变量.
如果将s1
和s2
声明为final
,则s3 == s5
将是true
.
If you declare s1
and s2
as final
, s3 == s5
would be true
.
这篇关于字符串文字和字符串对象之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!