Java: Boxed values and equality
An operator such as
<= is only defined for primitive types, so when applied to, say
Integers, the compiler will automatically unbox the operands.
Example: Operands are unboxed.
This is in fact the case for all operators except
!= operators are defined for reference types, the compiler is not forced to, and will not, unbox the operands.
Example: Operands are not unboxed (and
j refer to different objects)
To complicate matters further, autoboxing reuses cached objects for values between −128 and 127. This causes reference equality to "work" for some boxed values but not for others.
jrefer to the same object
lrefer to different objects
.equals will however always work as expected!
l refer to different objects
Recommendation: Never rely on
!= for boxed values. Always use
.equals or explicit unboxing.