Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is the == operator implemented in Java?

Tags:

java

jvm

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 address at the time of comparison? Or does it utilize the hashCode value of the two references to determine if the objects are the same?

To be very specific here, I would like to know what data structures managed by the JVM are referenced by the == operation for reference comparison. Does == rely on the OOP to perform reference comparison?

Unfortunately for me, the JLS does not define how the == operator must work. The Java API docs do not mention what == is supposed to do (they're for classes, right?)

PS: I was a bit intrigued by this question on hashcode uniqueness, and would prefer to know how the Sun JVM (or OpenJDK) implements the == operator.

like image 649
Vineet Reynolds Avatar asked Sep 05 '09 00:09

Vineet Reynolds


2 Answers

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.

like image 198
Reed Copsey Avatar answered Nov 14 '22 06:11

Reed Copsey


Because a reference is just a number, a reference comparison comes down to just comparing two numbers. No hash is needed.

like image 44
Mike Daniels Avatar answered Nov 14 '22 06:11

Mike Daniels