Search code examples
javascjpocpjp

Relation between equals() method and == operator


I know that == operator is applicable for content comparison for primitive types and reference comparison for objects.

Similarly, .equals() method of object class is for reference comparison of objects and content comparison in strings and wrapper classes.

But the following points which I took from SCJP/OCJP notes, I am not able to understand. I looked on the web and find only the differences between == and .equals but not the relation as how it is mentioned below.

  • If r1==r2 is true then r1.equals(r2) is always true.
  • If r1==r2 is false then r1.equals(r2) may return true (or) false.
  • If r1.equals(r2) is true then r1==r2 may return true (or) false.
  • If r1.equals(r2) is false then r1==r2 is always false.

Solution

  • These requirements ensure that the equals method will have the semantics that people expect for the concept of equivalence, and the logical/mathematical properties.

    So, we expect equivalence to be transitive: if A equals B and B equals C, then A equals C. And we expect symmetry: if A equals B then B equals A. And we expect equality to be reflexive: A equals A.