Versions Compared

Key

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

In the absence of autoboxing, the The values of boxed primitives cannot be directly compared using the == and != operators by default. This is because these are interpreted as reference comparison operators. This condition is demonstrated in the first noncompliant code example.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 2015], explains which primitive values are memoized during autoboxing Wiki MarkupAutoboxing on the other hand, can also produce subtle effects. It works by automatically wrapping the primitive type to the corresponding wrapper object. Some care should be taken during this process, especially when performing comparisons. The Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\] explains this point clearly:

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.

Use of the == and != operators for comparing the values of boxed 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.

Use of the == and != operators for comparing the values of boxed primitive types is not allowed in all other cases.

Note that Java Virtual Machine (JVM) implementations are allowed, but not required, to memoize additional values [JLS 2015]:

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.

Noncompliant Code Example

...

This noncompliant code example (adopted from \[[Bloch 2009|AA. Bibliography#Bloch 09]\]), defines a {{Comparator}} with a {{compare()}} method. The {{ method [Bloch 2009]. The compare()}} method accepts two boxed primitives as arguments. 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
bgColor#FFCCCC
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);
  } 
};

Note that primitive integers are also accepted by this declaration as because they are appropriately autoboxed. The main issue is that the == operator is being used to compare the two boxed primitives. However, this compares their references and not the actual valuesautoboxed at the call site.

Compliant Solution

To be compliant, use any of the four This compliant solution uses the comparison operators, <, >, <= and , or >=, because these cause automatic unboxing of the primitive values. The == and != operators should not be used to compare boxed primitives.

Code Block
bgColor#ccccff
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 guideline EXP01-J. Do not compare String objects using equality or relational operators, for == to return true for two object references, they must point to the same underlying object. Results of using the == operator in this case will be misleading.However, the == operator compares object references rather than object values.

Code Block
bgColor#FFCCCC

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);
 
 }
}

These comparisons generate the output sequence: true, false, false and true. The cache in the Integer class can only make the integers is guaranteed to cache only integer values from -127 to 128 refer to the same object, which explains the output of the above code. To avoid making such mistakes, use 127, which can result in equivalent values outside this range comparing 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 wrapper classes (See guideline EXP03-J for further details.)

Compliant Solution

Using object1.equals(object2) only compares the values of the objects. Now, the results will be true, The program now prints true, false, true, false on all platforms, as expected.

Code Block
bgColor#CCCCFF

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));
  }
}

Noncompliant Code Example

Sometimes a list of integers is desired. Recall that the type parameter inside the angle brackets of a list cannot be of a primitive type. It is not possible to form an ArrayList<int> that contains values of type int. With the help 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 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, it becomes possible to store integer values in an ArrayList<Integer> instance.

In this This noncompliant code example , it is desired attempts to count the integers number of indices in arrays list1 and list2. As that have equivalent values. Recall that class Integer only caches integers from -127 to 128, when an int value is beyond this range, it is autoboxed into the corresponding wrapper type. The == operator returns false when these distinct wrapper objects are compared. As a result, the output of this example is 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 for(int i = 0; i < 10; i++) {
      list1.add(i + 1000);
    }

    // Create another array list of integers, where each element
    // ishas the same value as the first list
    ArrayList<Integer> list2 = new ArrayList<Integer>();
   
  for 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)) {  // Uses '=='
        counter++;
      }
    }

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

}

If it were possible to expand the Integer cache (for example, caching all the values -32768 to 32767, which means that all However, if the particular JVM running this code memoized integer values from −32,768 to 32,767, all of the int values in the example would be have been autoboxed to cached the corresponding Integer objects), then the results may have differedand 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 lacks a specification of this interval; rather, it specifies a minimum range that must be memoized. Consequently, successful prediction of this program's behavior would require implementation-specific details of the JVM.

Compliant Solution

This compliant solution uses the equals() method for performing to perform value comparisons of wrapped objects. It produces the correct output, 10.

Code Block
bgColor#CCCCFF

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
    // ishas 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))) {  // Uses 'equals()'
        counter++;
      }
    }
 
    // Print the counter: 10 in this example
    System.out.println(counter);
  }
}

Exceptions

Noncompliant Code Example (Boolean)

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 resultsEXP03-EX1: Boolean variables can be compared using relational operators, however, if instantiated as an object this is counterproductive.

Code Block
bgColor#FFCCCC
public void exampleEqualOperator(){
  Boolean b1 = new Boolean("true");
  Boolean b2 = new Boolean("true");

  if (b1 == b2) {    // neverNever equal
  //  System...
}
out.println("Never printed");
  }
}

Compliant Solution (Boolean)

Boolean.TRUEBoolean.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.Use this instead:

Code Block
bgColor#CCCCFF
public void exampleEqualOperator(){
  Boolean b1 = true;
 // Or Boolean.True
Boolean b2 = true; 
	
  if (b1 == b2) {   // Or Always equal
    System.out.println("Always printed");
  }
 
  b1 = Boolean.TrueTRUE;
  if (b1 == b2) {     // alwaysAlways equal
   // System...out.println("Always printed");
  }
}

...

Risk Assessment

Using the equal and not equal equivalence operators to compare values of boxed primitives can lead to erroneous comparisons.

Guideline

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

EXP03-J

low

Low

likely

Likely

medium

Medium

P6

L2

Automated Detection

Detection

...

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Bibliography

Wiki Markup
\[[Bloch 2009|AA. Bibliography#Bloch 09]\] 4. "Searching for the One"
\[[Pugh 2009|AA. Bibliography#Pugh 09]\] Using == to compare objects rather than .equals

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
Include Page
CodeSonar_V
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
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

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 2015]

§5.1.7, "Boxing Conversion"

[Pugh 2009]

Using == to Compare Objects Rather than .equals

[Seacord 2015]


...

Image Added Image Added Image AddedEXP02-J. Do not use the equals method to compare the contents of arrays      04. Expressions (EXP)      EXP04-J. Be wary of invisible implicit casts when using compound assignment operators