The equals() method and == operator in Java perform two different operations. The equals() method is used to compare two string values. On the other hand == operator is used to compare two primitive datatype variables or to compare references of two objects. Below is a sample program that shows difference between equals() and == in Java.
Java中的equals()方法和==运算符执行两种不同的操作。 equals()方法用于比较两个字符串值。 另一方面,==运算符用于比较两个原始数据类型变量或比较两个对象的引用。 下面是一个示例程序,显示了Java中equals()和==之间的区别。
class EqualsAndEqualExample
{
public static void main(String...s)
{
String str1=new String("The Crazy Programmer");
String str2=new String("The Crazy Programmer");
System.out.println("str1 equals() str2 "+str1.equals(str2));
System.out.println("str1 == str2 "+(str1==str2));
}
}
Output
输出量
![Difference Between equals() and == in Java](https://i-blog.csdnimg.cn/blog_migrate/c8f68755ca155181eb841f6e1d18a75d.png)
In first case we are comparing the values or content of String objects str1 and str2 using equals() method. The result is true because there values are equal.
在第一种情况下,我们使用equals()方法比较String对象str1和str2的值或内容。 结果是正确的,因为那里的值相等。
In the second case we are comparing the references of String objects str1 and str2 using == operator. The result is false because there references are not equal as both the objects are different.
在第二种情况下,我们使用==运算符比较字符串对象str1和str2的引用。 结果为假,因为两个对象都不相同,所以引用不相等。
翻译自: https://www.thecrazyprogrammer.com/2015/08/difference-between-equals-and-in-java.html