Java: Boxed values and equality
When comparing wrapper types such as
!=, you're comparing them as references, not as values.
If two variables point at different objects, they will not
== each other, even if the objects represent the same value.
Example: Comparing different
Integer objects using
The solution is to compare the values using
Example: Compare objects using
…or to unbox the operands explicitly.
Example: Force unboxing by casting:
*, …), logical (
||, …), bitwise (
<<, …) and commparison operators other than
<=, …) are only defined for primitive types, so when applied to boxed types the compiler will automatically unbox the operands.
Example: Operands are unboxed.
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.
Example: 1 is within caching range, thus
j refer to the same object:
Example: 300 is not within caching range, thus
l refer to different objects: