Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does default equals implementation in java works for String? [duplicate]

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 ??

like image 990
Praveen Kumar Avatar asked Mar 23 '13 10:03

Praveen Kumar


2 Answers

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.

like image 195
Vishal K Avatar answered Oct 12 '22 22:10

Vishal K


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.

like image 45
Ankur Shanbhag Avatar answered Oct 12 '22 23:10

Ankur Shanbhag