The values of boxed primitives cannot be directly compared using the ==
and !=
operators because they these operators compare object references , not rather than object values. Programmers might 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 SpecificationSection 5 (JLS), §5.1.7, "Boxing Conversion" [JLS 2015], 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 |
The Use of the ==
and !=
operators may be used to compare for comparing the values of fully memoized boxed primitive types is permitted.
The Use of the ==
and !=
operators may only be used for comparing the values of boxed primitives primitive types that are not fully memoized is permitted only when the range of values represented is guaranteed to be within the ranges specified by the JLS to be fully memoized.In general, avoid using these operators to compare
Use of the ==
and !=
operators for comparing the values of boxed primitives that are not fully memoized.primitive types is not allowed in all other cases.
Note that Java Virtual Machine (JVM) implementations Implementations are allowed, but not required, to memoize additional values [JLS 2015]:
Less memory-limited implementations mightcould, for example, cache all characters and shorts, as well as integers and longs in the range of -32K - −32K to +32K. (§5.1.7)
Code that depends on implementation-defined behavior is not portablenonportable. It is permissible to depend on implementation-specific ranges of memoized values provided that all targeted implementations support these greater ranges.
Noncompliant Code Example
This noncompliant code example defines a {{ Wiki Markup Comparator
}} with a {{compare()
}} method \ [[Bloch 2009|AA. Bibliography#Bloch 09]\]. 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.
Code Block | ||
---|---|---|
| ||
import java.util.Comparator; static Comparator<Integer> cmp = new Comparator<Integer>() { public int compare(Integer i, Integer j) { return i < j ? -1 : (i == j ? 0 : 1); } }; |
...
This compliant solution uses the comparison operators, <
, >
, <=
, or >=
, because these cause automatic unboxing of the primitive values. The ==
and !=
operators should not be used to compare boxed primitives.
Code Block | ||
---|---|---|
| ||
import java.util.Comparator; static Comparator<Integer> cmp = new Comparator<Integer>() { public int compare(Integer i, Integer j) { return i < j ? -1 : (i > j ? 1 : 0) ; } }; |
Noncompliant Code Example
This noncompliant code example uses the ==
operator in an attempt to compare two the values of pairs of Integer
objects. According to the guideline EXP01-J. Do not confuse abstract object equality with reference equality, for However, the ==
operator to return true
for two object references, they must point to the same underlying objectcompares object references rather than object values.
Code Block | ||
---|---|---|
| ||
public class Wrapper {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 1000;
Integer i4 = 1000;
System.out.println(i1 == i2);
System.out.println(i1 != i2);
System.out.println(i3 == i4);
System.out.println(i3 != i4);
}
}
|
The Integer
class caches is guaranteed to cache only integer values from -128
to 127
to 128
only, which can result in equivalent values outside this range not comparing equalcomparing as unequal when tested using the equality operators. For example, a JVM that did not cache any other values when running this program would output:
Code Block |
---|
true
false
false
true
|
Compliant Solution
This compliant solution uses the equals()
method instead of the ==
operator to compare the values of the objects. The program now prints true
, false
, true
and , false
on any platformall platforms, as expected.
Code Block | ||
---|---|---|
| ||
public class Wrapper {
public static void main(String[] args) {
Integer i1 = 100;
Integer i2 = 100;
Integer i3 = 1000;
Integer i4 = 1000;
System.out.println(i1.equals(i2));
System.out.println(!i1.equals(i2));
System.out.println(i3.equals(i4));
System.out.println(!i3.equals(i4));
}
}
|
...
Java Collections contain only objects; they cannot contain primitive types. Further, the type parameters of all Java generics must be object types rather than primitive types. That is, attempting to declare an ArrayList<int>
(which, presumably, would presumably contains contain values of type int
) fails at compile time because type int
is not an object type. The appropriate declaration would be ArrayList<Integer>
, which makes use of the wrapper classes and autoboxing.
This noncompliant code example attempts to count the number of indices in arrays list1
and list2
that have equivalent values. Recall that class Integer
need is required to memoize only those integer values in the range -−128 to 127 to 128; it might return non-unique objects for all values a nonunique object for any value outside that range. Consequently, when comparing autoboxed integer values outside that range, the ==
operator might return false , and the output of this example might be example could deceptively output 0.
Code Block | ||
---|---|---|
| ||
public class Wrapper { public static void main(String[] args) { // Create an array list of integers, where each element // is greater than 127 ArrayList<Integer> list1 = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { list1.add(i + 1000); } // Create another array list of integers, where each element // has the same value as the first list ArrayList<Integer> list2 = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { list2.add(i + 1000); } // Count matching values. int counter = 0; for (int i = 0; i < 10; i++) { if (list1.get(i) == list2.get(i)) { // usesUses '==' counter++; } } // printPrint the counter: 0 in this example System.out.println(counter); } } |
If However, if the particular JVM running this code memoized integer values from -32−32,768 to 32,767, all of the int
values in the example would have been autoboxed to singleton the corresponding Integer
objects, and the example code would have operated as expected. Using reference equality instead of object equality requires that all values encountered fall within the interval of values memoized by the JVM. The JLS does not specify lacks a specification of this interval; rather, it only provides specifies a minimum range that must be memoized. Consequently, successful prediction of this program's behavior would require implementation-specific details of the JVM.
...
This compliant solution uses the equals()
method to perform value comparisons of wrapped objects. It produces the correct output, 10.
Code Block | ||
---|---|---|
| ||
public class Wrapper { public static void main(String[] args) { // Create an array list of integers, where each element // is greater than 127 ArrayList<Integer> list1 = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { list1.add(i + 1000); } // Create another array list of integers, where each element // has the same value as the first one ArrayList<Integer> list2 = new ArrayList<Integer>(); for (int i = 0; i < 10; i++) { list2.add(i + 1000); } // Count matching values int counter = 0; for (int i = 0; i < 10; i++) { if (list1.get(i).equals(list2.get(i))) { // usesUses 'equals()' counter++; } } // printPrint the counter: 10 in this example System.out.println(counter); } } |
Noncompliant Code Example (
...
Boolean
)
Constructors In this noncompliant code example, constructors for class Boolean
return distinct newly - instantiated objects. Using the reference equality operators in place of value comparisons will yield unexpected results.
Code Block | ||
---|---|---|
| ||
public void exampleEqualOperator(){ Boolean b1 = new Boolean("true"); Boolean b2 = new Boolean("true"); if (b1 == b2;) { // Never equal // never equalSystem.out.println("Never printed"); } } |
Compliant Solution (
...
Boolean
)
The values of autoboxed Boolean
variables Boolean.TRUE
, Boolean.FALSE
, or the values of autoboxed true
and false
literals, may be compared using the reference equality operators because the Java language guarantees that the Boolean
type is fully memoized. Consequently, these objects are guaranteed to be singletons.
Code Block | ||
---|---|---|
| ||
public void exampleEqualOperator(){ Boolean b1 = true; // Or Boolean.True Boolean b2 = true; if (b1 == b2) { // Or Boolean.True Always equal System.out.println("Always printed"); } b1 == b2Boolean.TRUE; if (b1 == b2) { // alwaysAlways equal |
Exceptions
...
System.out.println("Always printed");
}
}
|
Risk Assessment
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.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Bibliography
Wiki Markup |
---|
\[[Bloch 2009|AA. Bibliography#Bloch 09]\] 4. "Searching for the One"
\[[JLS 2005|AA. Bibliography#JLS 05]\] [Section 5.1.7|http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.7], "Boxing Conversion"
\[[Pugh 2009|AA. Bibliography#Pugh 09]\] Using == to compare objects rather than .equals |
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
CodeSonar |
| JAVA.COMPARE.EMPTYSTR | Comparison to Empty String (Java) | ||||||
Coverity | 7.5 | BAD_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] |
...
EXP02-J. Use the two-argument Arrays.equals() method to compare the contents of arrays 04. Expressions (EXP)