Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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 is true, false, a byte, a char in the range \u0000 to \u007f, or an int or short number between -128 and 127, then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Primitive Type

Boxed Type

Fully Memoized

boolean, byte

Boolean, Byte

Yes

char, short, int

Char, Short, Int

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.

...

This noncompliant code example attempts to count the number of indices in arrays list1 and list2 that have equivalent values. Recall that class Integer is required to memoize only those integer values in the range −128 to 127; it might return 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 example could deceptively output 0.

Code Block
bgColor#FFCCCC
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++;
      }
    }

    // Print the counter: 0 in this example
    System.out.println(counter);
  }

}

...

Code Block
bgColor#CCCCFF
public class Wrapper {
  public static void main(String[] args) {
    // Create an array list of integers
    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++;
      }
    }
 
    // Print the counter: 10 in this example
    System.out.println(counter);
  }
}

...

Boolean.TRUEBoolean.FALSE, or the values of autoboxed true and false literals 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.

...

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
Coverity
CodeSonar
7.5
Include Page
BAD
CodeSonar_
EQ
V
FB.EQ_ABSTRACT_SELF
FB.EQ_ALWAYS_FALSE
FB.EQ_ALWAYS_TRUE
CodeSonar_V

JAVA.COMPARE.EMPTYSTR
JAVA.COMPARE.EQ
JAVA.COMPARE.EQARRAY

Comparison to Empty String (Java)
Should Use equals() Instead of == (Java)
equals on Array (Java)

Coverity7.5

BAD_EQ
FB.EQ_ABSTRACT_SELF
FB.EQ_ALWAYS_FALSE
FB.EQ_ALWAYS_TRUE
FB.EQ_CHECK_FOR_OPERAND_NOT_ COMPATIBLE_WITH_THIS
FB.EQ_COMPARETO_USE_OBJECT_ EQUALS
FB.EQ_COMPARING_CLASS_NAMES
FB.EQ_DOESNT_OVERRIDE_EQUALS
FB.EQ_DONT_DEFINE_EQUALS_ FOR_ENUM
FB.EQ_GETCLASS_AND_CLASS_ CONSTANT
FB.EQ_OTHER_NO_OBJECT
FB.EQ_OTHER_USE_OBJECT
FB.EQ_OVERRIDING_EQUALS_ NOT_SYMMETRIC
FB.EQ_SELF_NO_OBJECT
FB.EQ_SELF_USE_OBJECT
FB

.EQ_UNUSUAL

.EQ_UNUSUAL
FB.ES_COMPARING_PARAMETER_ STRING_WITH_EQ
FB.ES_COMPARING_STRINGS_ WITH_EQ
FB.ES_COMPARING_PARAMETER_ STRING_WITH_EQ


FB.ES_COMPARING_STRINGS_ WITH_EQ
FB.ES_COMPARING_PARAMETER_ STRING_WITH_EQ

Implemented
Parasoft Jtest
Include Page
Parasoft_V
Parasoft_V
CERT.EXP03.UEICDo not use '==' or '!=' to compare objects
PVS-Studio

Include Page
PVS-Studio_V
PVS-Studio_V

V6013
SonarQube
Include Page
SonarQube_V
SonarQube_V
S1698"==" and "!=" should not be used when "equals" is overridden
Implemented

Related Guidelines

MITRE CWE

CWE-595, Comparison of Object References Instead of Object Contents
CWE-597, Use of Wrong Operator in String Comparison

Bibliography

[Bloch 2009]

Puzzle 4, "Searching for the One"

[JLS

2005

2015]

§5.1.7, "Boxing Conversion"

[Pugh 2009]

Using == to Compare Objects Rather than .equals

[Seacord 2015]

...


...

Image Modified Image Modified Image Modified