The values of boxed primitives cannot be directly compared using the ==
and !=
operators because these operators compare object references rather than object values. Programmers can 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.
Autoboxing automatically wraps a value of a primitive type with the corresponding wrapper object. The Java Language Specification (JLS) §5.1.7, "Boxing Conversion," [JLS 2005], explains which primitive values are memoized during autoboxing:
...
This noncompliant code example defines a Comparator
with a compare()
method [Bloch 2009]. The compare()
method accepts two boxed primitives as arguments. The ==
operator is used to compare the two boxed primitives. In this context, however, it compares the references to the wrapper objects rather than comparing the values held in those objects.
...
CWE-595. Comparison of object references instead of object contents | |
| CWE-597. Use of wrong operator in string comparison |
Bibliography
4, Searching for the One | |
[JLS 2005] | |
Using == to Compare Objects Rather than |
...