关于Java相等运算符的使用

可能重复:
如何比较Java中的字符串?

class StringTest { public static void main(String[] args) { String str1 = "Hi there"; String str2 = new String("Hi there"); System.out.println(str1 == str2); System.out.println(str1.equals(str2)); } 

输出结果出来:

  False true 

为什么即使str1和str2看起来相等,第一个输出也是假的?

==比较变量的内容。 (从intA == intB你很清楚这intA == intB 。)

String变量包含对String对象的引用 ,因此==将比较引用。

 String str1 = "Hi there"; String str2 = new String("Hi there"); 

str1str2将引用不同的字符串对象,因此包含不同的引用,因此str1 == str2将产生false

str1.equals(str2)将比较str1str2引用的对象,正如您所指出的,它们会产生true

因为如果使用new运算符,它会在内存中创建一个新引用。

==比较两个不相同的对象的引用。

使用equals来比较内容。

作为aioobe答案的补充:你应该使用equals方法比较对象。 对象上的==运算符将比较两个对象的引用是否指向相同的内存地址。

在java中,当您使用new关键字创建对象时,它们会在某个位置的堆中创建。

即使您使用new创建第三个引用变量str3 ,如果与str2进行比较引用,它也会给出错误

 String str1 = "Hi there"; String str2 = new String("Hi there"); String str3 = new String("Hi there"); str2==str3 gives you false 

所以当你compare object的值时,使用equals而不是reference

==比较object reference contentsstr1str2而不是object contentsequals()比较object contents(objects pointed by str1 and str2)

还检查一下:

 String str1 = "Hi there"; String str3 = "Hi there"; 

str1 == str3 => true

这是因为JVM以不同的方式处理字符串文字。 点击这里