Showing posts with label java equals method code. Show all posts
Showing posts with label java equals method code. Show all posts

Thursday, 30 July 2015

Difference between == and .equals()

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


 if(s1.equals(s2))
      System.out.println("s1.equals(s2) is TRUE");
 else
      System.out.println("s1.equals(s2) is FALSE");
You will get the output as TRUE as the 'equals()' method check for the content equivality.

Lets check the '==' operator.


if(s1==s2)
     System.out.printlln("s1==s2 is TRUE");
   else
     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.