The equality operators
are used with both primitive types and object references.
They return a
value indicating whether or not the operands are "equal." When testing for equality,
you should keep the following important points in mind:
- Numeric values are promoted before being compared.
- Numeric values cannot be compared to
- Object references are checked to see if they refer to the same object and not whether they have the same value.
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.
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
Object objects using the
If a program contains two
s2 with equal values,
s1.equals(s2) returns true.
However, the following
s1 == s2 will return true if and only if
s2 reference the same object in memory.
The following question will deepen your understanding of the equals() method in Java.
Assume that a, b, and c refer to instances of primitive wrapper classes.
Which of the following statements are correct?
- a.equals(a) will always return true.
- b.equals(c) may return false even if c.equals(b) returns true.
- a.equals(b) returns same as a == b.
- a.equals(b) throws an exception if they refer to instances of different classes
- a.equals(b) returns false if they refer to instances of different classes.
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
- reflexive => a.equals(a) return true.
- symmetric => a.equals(b) returns the same result as b.equals(a)
- 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.