== operator is used to compare the references of the objects.
public boolean equals(Object o) is the method provided by the Object class. The default implementation uses ==
operator to compare two objects.
But since the method can be overridden like for String class. equals() method can be used to compare the values of two
objects.
String str1 = new String("MyName");
String str2 = new String("MyName");
if(str1 == str2){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}
if(str1.equals(str2)){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}
Output:
Objects are not equal
Objects are equal
Lets look at other snippet:
String str2 = "MyName";
String str3 = str2;
if(str2 == str3){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}
if(str3.equals(str2)){
System.out.println(“Objects are equal”)
}else{
System.out.println(“Objects are not equal”)
}
Objects are equal
Objects are equal