seriously divergent seriously divergent - 3 months ago 7
Java Question

equals() method of objects is acting different with String objects and the Objects I created?

I am confused with .equals() method for objects in the case 2 and case 3. For the case 1, I can understand that references and the contents are the same, so we got the true, true respectively.

In the case 2, equals() method compares the type and content, and returns true (according to documentation, it first compare the object type and then compares the content). However in the 3rd case, even if the types and contents are the same, it returns False! ?
Is there any special feature of the String object? Any help/ hint/ explanation is appreciated.

public class equalMethods {

static class MyObject {

String name;

// constructor
MyObject(String s) {
this.name = s;
}
}

public static void main(String[] args) {

// ***CASE 1****
String a = "str1";
String b = "str1";
System.out.println(a == b); // True
System.out.println(a.equals(b));// True
System.out.println();

// ***CASE 2****
String an = new String("oracle");
String bn = new String("oracle");
System.out.println(an == bn); // False
System.out.println(an.equals(bn));// True ( ? Compare with case 3)
System.out.println();

// // ***CASE 3****
MyObject object1 = new MyObject("str1");
MyObject object2 = new MyObject("str1");
System.out.println(object1 == object2); // False
System.out.println(object1.equals(object2)); // False ( ? Compare with case 2)
System.out.println();

}

}

Answer

The general behavior is, equals() is inherited from Object class into all the java class with its default implementation. All the classes should provide the equality as required for their objects. So if you are writing any custom class (usually POJO) which uses collection framework or uses instance equality, then you should implement the equals() method on the respective instance members.

Object object1 = new Object("sam");
Object object2 = new Object("sam");
System.out.println(object1 == object2); // False
System.out.println(object1.equals(object2)); // False ( ? Compare with case 2) 

Because here it is calling the equals() method from the Object class. Which check the reference equality only. Both the objects are different and so false.


String an = new String("oracle");
String bn = new String("oracle");
System.out.println(an == bn); // False
System.out.println(an.equals(bn));// True ( ? Compare with case 3)

Here the equals() implementation from String class is invoked, which checks for reference equality and content equality as well so it matches and returns true.


If you are overriding the behavior of equals() for any class, it is recommended to override hashCode() method as well.