In the above code, == is used to compare the bit pattern/values of an Integer object with an int primitive. It looked like from the result that Integer object is unboxed and then both the primitives values' are checked for equality thereby resulting in value true.
Q. Why is an Integer object being unboxed as opposed to primitive being boxed instead (in which case the result would have been false)?
Regards Ravinder Singh
posted 10 years ago
Everything is driven by the Java Language Specification:
15.21.1 Numerical Equality Operators == and != 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).
So the Integer object is unboxed to an int and a binary comparison takes place on the two operands. In comparing two entities representing numeric values, the most logical thing (to me) is to compare their values not their arbitrary memory addresses. Unboxing the Integer to an int is more optimal performance wise, than boxing the int and then comparing the numerical values of two Integer objects (which would anyway be a binary comparison).