[英]Reference equality for String literals
I have the following code snippet.I am getting the output as false
for the reference equality of the strings s1
and s2
. 我有以下代码片段。我得到输出为false
为字符串s1
和s2
的引用相等。
Should not this be true
? 这不应该是true
吗? Strings are immutable in Java and when I create s2
with the same content as s1
(I hate Winters), the reference s2
will simply point to the already existing String object which is being pointed by s1
. 字符串在Java中是不可变的,当我使用与s1
相同的内容创建s2
时(我讨厌Winters),引用s2
将简单地指向s1
指向的已存在的String对象。
public static void main(String[] args) {
String s1="I hate";
s1=s1+" Winters";
String s2="I hate Winters";
System.out.println(s1==s2);
}
In your program, calculations are made at runtime, the compiler doesn't know that s1
and s2
will be equal strings, so it won't be part of the constant pool. 在你的程序中,计算是在运行时进行的,编译器不知道s1
和s2
将是相等的字符串,因此它不会成为常量池的一部分。 If you do: 如果你这样做:
String s1 = "I hate Winters";
String s2 = "I hate" + " Winters";
Concatenation will occur at compile time, and they'll point to the same literal in the pool. 连接将在编译时发生,它们将指向池中的相同文字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.