What do you use in Java to check if two things are equal or not? And what’s exactly the meaning of being equal?

OK, you already probably know that you can use the operator == to compare primitives and objects. If you’ve read about the equals-hashCode contract you probably also know that you can compare objects using the method equals.

However there are some important and little subtleties you must know about equality comparison before trying the exam. Let’s say you have the following code:

These are the 5 things you must remember:

  1. i1 == i2 will return false because they are pointing to different objects.
  2. i1 == i3 will return true because one operand is a primitive int and so the other will be unboxed and then the value will be compared.
  3. i1 == b1 will not even compile because type of i1 and b1 references are classes that are not in the same class hierarchy, so the compiler knows that they can’t point to the same object.
  4. i1.equals(i2) will return true because both are Integer and both have a value of 1.
  5. i1.equals(b1) and i1.equals(g1) will return false because they are pointing to objects of different types. The signature of the equals method is boolean equals(Object o) so it can take any object and there will be no compilation error. However the equals method of all wrapper classes first checks if the two objects are of same class and if they aren’t, it immediately returns false.

 

 


Leave a Reply