We all know if we create two String objects and use == to compare them it will return false and if we use equals to method it will return true. But by default equals method implement == only , then how does it return true , it should return whatever == is returning ??
Yes by default equals method implements == in Object class . But you can Override the equals method in your own class to change the way equality is done between two objects of the same class. For example the equals method in String class is overridden as follows:
public boolean equals(Object anObject) {
          if (this == anObject) {
              return true;
          }
          if (anObject instanceof String) {
              String anotherString = (String)anObject;
              int n = count;
              if (n == anotherString.count) {
                  char v1[] = value;
                  char v2[] = anotherString.value;
                  int i = offset;
                  int j = anotherString.offset;
                  while (n-- != 0) {
                      if (v1[i++] != v2[j++])
                          return false;
                  }
                  return true;
              }
          }
          return false;
      }
So this is the reason that for the following code:
String s1 = new String("java");
String s2 = new String("java");
s1==s2 returns false since both are referencing different objects on heap. Whereas s1.equals(s2) returns true since now the equals being called is what defined within String class where String objects are compared on the basis of contents of String.
the equals method in the String class is overridden and it tries to check if all the characters in both the Strings are equal or not. If found then it returns true. So the behavior of equals method in String class is different from the normal object class implementation of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With