...
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 20052015], explains which primitive values are memoized during autoboxing:
If the value
p
being boxed istrue
,false
, abyte
, achar
in the range\u0000
to\u007f
, or anint
orshort
number between-128
and127
, then letr1
andr2
be the results of any two boxing conversions ofp
. It is always the case thatr1 == r2
.
Primitive Type | Boxed Type | Fully Memoized |
---|---|---|
|
| Yes |
|
| No |
Use of the ==
and !=
operators for comparing the values of fully memoized boxed primitive types is permitted.
...
Note that Java Virtual Machine (JVM) implementations are allowed, but not required, to memoize additional values [JLS 20052015]:
Less memory-limited implementations could, for example, cache all characters and shorts, as well as integers and longs in the range of −32K to +32K. (§5.1.7)
Code that depends on implementation-defined behavior is nonportable. It is permissible to depend on implementation-specific ranges of memoized values provided that all targeted implementations support these greater ranges.
...
Using the equivalence operators to compare values of boxed primitives can lead to erroneous comparisons.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
EXP03-J | Low | Likely | Medium | P6 | L2 |
Automated Detection
Detection of all uses of the reference equality operators on boxed primitive objects is straightforward. Determining the correctness of such uses is infeasible in the general case.
Tool | Version | Checker | Description |
---|
CodeSonar |
|
|
|
FB.EQ_ALWAYS_FALSE
FB.EQ_ALWAYS_TRUE
| JAVA.COMPARE.EMPTYSTR | Comparison to Empty String (Java) | |||
Coverity | 7.5 | BAD_EQ |
FOR_OPERAND_NOT_ COMPATIBLE_WITH_THIS |
FB.EQ_UNUSUAL
_USE_OBJECT |
FB.ES_COMPARING_STRINGS_ WITH_EQ
FB.ES_COMPARING_PARAMETER_ STRING_WITH_EQ
Implemented | |||||||||
Parasoft Jtest |
| CERT.EXP03.UEIC | Do not use '==' or '!=' to compare objects | ||||||
PVS-Studio |
| V6013 | |||||||
SonarQube |
| S1698 | "==" and "!=" should not be used when "equals" is overridden |
Related Guidelines
CWE-595, Comparison of Object References Instead of Object Contents |
Bibliography
Puzzle 4, "Searching for the One" | |
[JLS |
2015] | |
Using == to Compare Objects Rather than | |
[Seacord 2015] |
...
...