Relation Between == Operator and equals() Method
Understanding relation between == Operator and equals() method
The == operator is an essential operator in Java, and it is used for reference comparison, whereas the equals() method is a method of the Object class, which is Java’s root or parent class, and it may be overridden as needed by the developer.
Here below, I would like to describe the relationship between the == operator and the equals() method -
When two objects are equal with the == operator, they are always equal with equals() method. In other words, if r1 == r2 is true, then r1.equals(r2) is always true.
When two objects are not equal by the == operator, we cannot draw any conclusions about the equals() method, which may return true or false. That is, if r1 == r2 is false, then r1.equals(r2) may return true or false; we can’t be guaranteed.
We can’t conclude anything about the == operator if two objects are equal using the equals() method. It may return true or false. If r1.equals(r2) is true, we can’t draw any conclusions about r1 == r2, which might return true or false.
When two objects are not equal according to the equals() method, then they are not equal according to the == operator. That is, if r1.equals(r2) is false, r1 == r2 is also false.
In conclusion, use the == operator for reference comparison and the equals() method for content comparison.