Specifically, in the case of object reference equality, what does the == operator do?
Does the comparison return true if the references evaluate to the same object a
The == operator just compares the references.
References in the JVM are just a standard object pointer. This works out to a single 32bit or 64bit integer value (depending on platform).
When you compare two object references, you're really just comparing two 32bit or 64bit integers, and if they're the same, you'll equate to equal. The integer values are a location in memory.
The == operator returns true if the objects are the same object. There is not access to hashCode() or equals() here.
Try this to confirm:
public class Test {
static void testEqualEqual(Integer I0, Integer I1, boolean IsEquals) {
if(!(IsEquals == (I0 == I1)))
throw new AssertionError();
}
static void testEqual(Integer I0, Integer I1, boolean IsEquals) {
if(!(IsEquals == (I0.equals(I1))))
throw new AssertionError();
}
static void testHash(Integer I0, Integer I1, boolean IsEquals) {
if(!(IsEquals == (I0.hashCode() == I1.hashCode())))
throw new AssertionError();
}
public static void main(String ... args) {
testEqualEqual( 1, 1, true);
testEqualEqual(2000, 2000, false);
testEqual( 1, 1, true);
testEqual(2000, 2000, true);
testHash( 1, 1, true);
testHash(2000, 2000, true);
System.out.println("Done");
}
}
To understand this, you should know first that the number number 255 will be cached when autoboxed. This means that Integer of 1 is always the same object but Integer of 2000 will always be different object.
This experiment shows that '==' return true when the objects are the same. In case of '1' they are the same number and it returns true. But in case of '2000' autoboxed to be different objects so it returns false.
The experiment also shows that '==' does not use equals() or hashCode().
Hope this helps.
The ==
operator compares object references to see if they are identical, i.e. they refer to the same object in memory.
The equals()
method compares object references to see if they are equivalent, though not necessarily identical. The default implementation of equals()
uses the ==
operator, but it often makes sense to override this behavior. For example, you might want two BankAccount references to be considered equivalent if they have the same account number, even if they are completely different objects.
Because a reference is just a number, a reference comparison comes down to just comparing two numbers. No hash is needed.