I am wondering what is the internal Java behaviour for the next snippet:
Long a = 123L;
long b = 123;
System.out.println("a equals b?: " + (a == b));
The result is true
although comparing two Long
objects would be false
(because it compares their reference). It is Java converting Long
object into its primitive value because detects ==
operator against another primitive object?
It is Java converting Long object into its primitive value because detects == operator against another primitive object?
Yes. One of the operands is a primitive type and the other operand is convertible to a primitive by unboxing.
JLS section 15.21.1 says (emphasis mine):
If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).
Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).
Also, it is important to note that reference equality is only performed if both operands are objects. JLS section 15.21.3 says:
If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With