What is difference between equals() and == ?

Explanation : 1

They both differ very much in their significance. equals() method is present in the java.lang.Object class and it is expected to check for the equivalence of the state of objects! That means, the contents of the objects. Whereas the ‘==’ operator is expected to check the actual object instances are same or not.

For example, lets say, you have two String objects and they are being pointed by two different reference variables s1 and s2.

 s1 = new String("abc");
 s2 = new String("abc");

Now, if you use the “equals()” method to check for their equivalence as

      System.out.println("s1.equals(s2) is TRUE");
      System.out.println("s1.equals(s2) is FALSE");

You will get the output as TRUE as the ‘equals()’ method check for the content equality.

Lets check the ‘==’ operator..

     System.out.printlln("s1==s2 is TRUE");
     System.out.println("s1==s2 is FALSE");

Now you will get the FALSE as output because both s1 and s2 are pointing to two different objects even though both of them share the same string content. It is because of ‘new String()’ everytime a new object is created.

Try running the program without ‘new String’ and just with

   String s1 = "abc";
   String s2 = "abc";

You will get TRUE for both the tests. Explanation : 2

By definition, the objects are all created on the heap. When you create an object, say,

Object ob1 = new SomeObject();
Object ob2 = new SomeObject();

We have 2 objects with exactly the same contents, lets assume. We also have 2 references, lets say ob1 is at address 0x1234 and ob2 is at address 0x2345. Though the contents of the objects are the same, the references differ.

Using == compares the references. Though the objects, ob1 and ob2 are same internally, they differ on using this operation as we comare references. ob1 at address 0x1234 is compared with ob2 at address 0x2345. Hence, this comparison would fail.

object.equals() on the other hand compares the values. Hence, the comparison between ob1 and ob2 would pass. Note that the equals method should be explicitly overridden for this comparison to succeed.

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!