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
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:
Integer i1 = 1;
Integer i2 = new Integer(1);
int i3 = 1;
Byte b1 = 1;
Long g1 = 1L;
These are the 5 things you must remember:
i1 == i2will return
falsebecause they are pointing to different objects.
i1 == i3will return
truebecause one operand is a primitive
intand so the other will be unboxed and then the value will be compared.
i1 == b1will not even compile because type of
b1references are classes that are not in the same class hierarchy, so the compiler knows that they can’t point to the same object.
truebecause both are
Integerand both have a value of
falsebecause 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
equalsmethod of all wrapper classes first checks if the two objects are of same class and if they aren’t, it immediately returns