Classes/Objects  «Prev  Next»

Lesson 6 Testing for equality
ObjectiveDescribe equality operators and equals() method
Describe how the equality operators and the equals() method are used to compare objects.

Equality

The equality operators == and != are used with both primitive types and object references. They return a boolean value indicating whether or not the operands are "equal." When testing for equality, you should keep the following important points in mind:
  1. Numeric values are promoted before being compared.
  2. Numeric values cannot be compared to boolean values.
  3. Object references are checked to see if they refer to the same object and not whether they have the same value.
  4. The equals() method should be used to determine whether two objects have the same values.
The first rule is important because it allows any numeric value to be compared to any other numeric value. You will probably see some exam questions that will require you to know this. Keep the second rule in mind in case you see a numeric value being compared to a boolean value.
You will definitely see questions related to the last two rules.
The equals() method of the Object class is extended by subclasses to allow objects to be compared based on their values.
One of the exam objectives requires you to be able to determine the results of comparing String, Boolean, and Object objects using the equals() method.
If a program contains two String objects s1 and s2 with equal values, s1.equals(s2) returns true.
However, the following s1 == s2 will return true if and only if s1 and s2 reference the same object in memory.

The following question will deepen your understanding of the equals() method in Java.
Scenario: Assume that a, b, and c refer to instances of primitive wrapper classes.
Question: Which of the following statements are correct?
  1. a.equals(a) will always return true.
  2. b.equals(c) may return false even if c.equals(b) returns true.
  3. a.equals(b) returns same as a == b.
  4. a.equals(b) throws an exception if they refer to instances of different classes
  5. a.equals(b) returns false if they refer to instances of different classes.


Answer: 1, 5
Explanation:
3. The wrapper classes's equals() method overrides Object's equals() method to compare the actual value instead of the reference.
4. It returns false in such a case.
The equals() method of a primitive wrapper class contains the characteristics of an equivalence relation.
Equals method of a primitive wrapper class (i.e. java.lang.Integer, Long, Double, Float etc) are
  1. reflexive => a.equals(a) return true.
  2. symmetric => a.equals(b) returns the same result as b.equals(a)
  3. transitive => if a.equals(b) and b.equals(c) return true, then a.equals(c) returns true.
For option 1 for the question above contains the reflexive property.