The values of boxed primitives cannot be directly compared using the == and != operators because they compare object references, not object values. Programmers could find this behavior surprising because autoboxing memoizes or caches, the values of some primitive variables. Consequently, reference comparisons and value comparisons produce identical results for the subset of values that are memoized.
| Wiki Markup |
|---|
Autoboxing automatically wraps a value of a primitive type with the corresponding wrapper object. The [Section 5.1.7 "Boxing Conversion,"|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.7] of the _Java Language Specification_ \[[JLS 2005|AA. Bibliography#JLS 05]\] explains which primitive values are memoized during autoboxing: |
If the value
pbeing boxed istrue,false, abyte, acharin the range\u0000to\u007f, or anintorshortnumber between-128and127, then letr1andr2be the results of any two boxing conversions ofp. It is always the case thatr1 == r2.
...