Friday, 1 December 2017

Equals() method & == Operators

Equals() method & == Operators,Relationship between .equals() method and ==(double equal operator),Differences between == (double equal operator) and .equals() method?,what is equals() method in java, == operator in java ,


Differences between == (double equal operator) and .equals() method?


== (DOUBLE EQUAL OPERATOR)
.EQUALS() METHOD
It is an operator applicable for both primitives and object references.
It is a method applicable only for object references but not for primitives.
In the case of primitives == (double equal operator) meant for content comparison, but in the case of object references == operator meant for reference comparison. 
By default .equals() method present in object class is also meant for reference comparison.
We can't override== operator for content comparison in object references.
We can override .equals() method for content comparison.
If there is no relationship between argument types then we will get compile time error saying incompatible types.(relation means child to parent or parent to child or same type)
If there is no relationship between argument types then .equals() method simply returns false and we won't get any compile time error and runtime error.
For any object reference r, r==null is always false.
For any object reference r, r.equals(null) is also returns false.

Example:-


String s1 = new String("ashok"); String s2 = new String("ashok"); System.out.println(s1==s2);  //false System.out.println(s1.equals(s2) );  //true

StringBuffer s1 = new StringBuffer("ashok"); StringBuffer s2 = new StringBuffer("ashok"); System.out.println(s1==s2);  //false System.out.println(s1.equals(s2) );  //false


Relationship between .equals() method and ==(double equal operator) :

  1. If r1==r2 is true then r1.equals(r2) is always true i.e., if two objects are equal by == operator then these objects are always               equal by .equals( ) method also.

 2. If r1==r2 is false then we can't conclude anything about r1.equals(r2) it may return true (or) false. 
3. If r1.equals(r2) is true then we can't conclude anything about r1==r2 it may returns true (or) false.
4. If r1.equals(r2) is false then r1==r2 is always false.


Eg:-
String s = new String("ashok");
 StringBuffer sb = new StringBuffer("ashok"); System.out.println(s == sb); // CE : incomparable types : String and  StringBuffer
System.out.println(s.equals(sb));    //false


Note:  in general we can use == (double equal operator) forreference comparison whereas .equals() method for content comparison. 



DashZin

Author & Editor

Has laoreet percipitur ad. Vide interesset in mei, no his legimus verterem. Et nostrum imperdiet appellantur usu, mnesarchum referrentur id vim.

2 comments: