如果 == 比较 Java 中的引用,为什么用这些字符串计算结果为真? [英] If == compares references in Java, why does it evaluate to true with these Strings?
问题描述
正如前面所说,== 运算符比较对象引用以检查它们是否引用了堆上的同一个对象.如果是这样,为什么我会得到这段代码的相等"?
As it is stated the == operator compares object references to check if they are referring to the same object on a heap. If so why am I getting the "Equal" for this piece of code?
public class Salmon {
public static void main(String[] args) {
String str1 = "Str1";
String str2 = "Str1";
if (str1 == str2) {
System.out.println("Equal");
} else {
System.out.println("Not equal");
}
}
}
推荐答案
程序将打印 Equal
.(至少使用 Sun Hotspot 和 suns Javac.)这里它在 http://ideone.com/8UrRrk
这是因为字符串常量存储在字符串池中,并且字符串引用可以被重用.
This is due to the fact that string-literal constants are stored in a string pool and string references may be reused.
进一步阅读:
然而:
public class Salmon {
public static void main(String[] args) {
String str1 = "Str1";
String str2 = new String("Str1");
if (str1 == str2) {
System.out.println("Equal");
} else {
System.out.println("Not equal");
}
}
}
将打印 Not equal
因为 new
保证引入一个新的引用.
Will print Not equal
since new
is guaranteed to introduce a fresh reference.
所以,经验法则:始终使用 equals
方法比较字符串.
So, rule of thumb: Always compare strings using the equals
method.
这篇关于如果 == 比较 Java 中的引用,为什么用这些字符串计算结果为真?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!