Sunday, 5 August 2018

SE - 31 - Difference between .equals() and "==" operator


=> .equals
i) Its a method
ii) It can only be used for object comparison
iii) It does not looks for memory reference rather it looks for the objects(contents)

=> "=="
i) Its an operator (equality operator)
ii) It can be used for primitive as well as object comparison
iii) "==" compare two objects based on their memory reference(or address). It will return true only if two object has same reference or the reference it is comparing represent exactly same object . In the situation where the object reference are different then it will return false.

Example :

public class equalDotEquals {

 @Test
 public void equals() {
  
  Integer I1 = new Integer(10);
  Integer I2 = new Integer(10);
  System.out.println((I1==I2));
  System.out.println((I1.equals(I2)));
  //Now we are making the same reference
  I1=I2;
  System.out.println("-----------------------");
  System.out.println((I1==I2));
  System.out.println((I1.equals(I2)));
 }
}
Output of above program :

false
true
-----------------------
true
true


Here we can see that we created two objects I1 and I2  of Integer. We applied "==" and ".equals()" operator on it. The output of "== " is false but output of ".equals()" is true . The reason is that "==" is using reference for comparison but reference of both the objects are different so its showing false. But equal() method compares the content(object) so its showing true.
Now we made the references of both the variable same by using I1=I2. now both the operators are giving same output.

No comments:

Post a Comment