Saturday, April 2, 2016

Difference : == operator and .equals() method

             This is the most common question asked in the interview for fresher as well as experienced.Most of  time interviewer person expect answer in one line like,  ==  operator meant for address or reference comparison and  .equals()  method meant for content comparison.

What is reference comparison and content comparison ?  


String s1 = new String("madhav");
String s2 = new String("madhav");
//case 1
System.out.println(s1==s2);
//case 2
System.out.println(s1.equals(s2));


  • As depict in above figure, both variable are pointing to two different memory reference but  having same contents.
  • case1 will return false where  ==  operator used, as the reference or memory address is not same.
  • case 2 will return true  where .equals() method used, the content of both variable are exactly same 
  • Following figure show both variable pointing to the same memory address or reference.
String s1 = new String("someValue");
String s2 = new String(s1);
String s3 = s2;

//case 1 : checking references

System.out.println(s1==s2);
System.out.println(s1==s3);
System.out.println(s2==s3);


//case 2 : checking content

System.out.println(s1.equals(s2));
System.out.println(s2.equals(3));
  • Here in case 1, same reference is shared by only s1 and s3, hence the result of  ==   operator is true.
  •  new  keyword used for creating s2, So different address is allocated. Therefore the result of  ==   operator on s2 and s1 is false.
  • For case 2  .equals()  method will return true as the contents are all same.
Note :
  •  .equals()  method present in Object class also meant for reference comparison only based on our requirement we can override for reference comparison.
  • In String class, all wrapper class and all collection classes  .equals()  method is overridden for content comparison. 

No comments:

Post a Comment