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 operators are interpreted as reference comparison operators. This condition is demonstrated in the first noncompliant code example.Programmers may find this surprising, however, because autoboxing memoizes the values of some primitive values. 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 Autoboxing on the other hand, can also produce subtle effects. It works by automatically wrapping the primitive type to the corresponding wrapper object. Care should be taken during this process, especially when performing comparisons. The Java Language Specification Section 5.1.7 Boxing Conversion explains which values can be safely comparedprimitive 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.

Noncompliant Code Example

Wiki Markup
This noncompliant code example (\[[Bloch 2009|AA. Bibliography#Bloch 09]\]), defines a {{Comparator}} with a {{compare()}} method. The {{compare()}} method accepts two boxed primitives as arguments. The problem is the use of the {{==}} operator to compare the two boxed primitives; in this context it compares the _references_ to the wrapper objects rather than comparing the _values_ held in those objects.  By comparison, the {{\<}} operator causes automatic unboxing of the primitive values and consequently operates as expected.

Code Block
bgColor#FFCCCC
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 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 valuesat the call site.

Compliant Solution

To be compliant, use any of the four comparison operators <, >, <= and >= since these force cause automatic unboxing of the primitive values to be automatically unboxed. The == and != operators should not be used to compare boxed primitives.

Code Block
bgColor#ccccff
public int compare(Integer i, Integer j) {
  return i < j ? -1 : (i > j ? 1 : 0) ;
}

Noncompliant Code Example

This code uses == to compare two Integer objects. According to guideline EXP01-J. Do not confuse abstract object equality with reference equality, 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.

...

These comparisons generate the output sequence: true, false, false and true. The cache in the Integer class can only make the integers memoizes integer values from -127 to 128 refer to the same object only, which explains the output of the above code. To avoid making such mistakes, use Avoid this problem by using the equals() method instead of == to compare wrapper classes (. See guideline EXP03-J for further details.)

Compliant Solution

Using This compliant solution uses object1.equals(object2) only compares to compare the values of the objects. Now, the results will be true, The results are now true, false, true and false, 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 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 would presumably contains values of type int. With the help ) fails at compile time because type int is not an object type. An important use of the wrapper classes and autoboxing , it becomes possible is to store integer values in an ArrayList<Integer> instance.

In this This noncompliant code example , it is desired attempts to count the number of integers of in arrays list1 and list2. As that have corresponding values. Recall that class Integer only caches integers from memoizes only those integer values in the range -127 to 128, when an int value is beyond this range, it is autoboxed into the corresponding wrapper type. The ; it returns non-unique objects for all values outside that range. Consequently, when comparing autoboxed integer values outside that range, the == operator returns false when these distinct wrapper objects are compared. As a result, {{false}, and the output of this example is 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
   // 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)) { 
       counter++;
     }
   }

   // print 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 the JLS specified the range of memoized integer values as -32768 to 32767, for example, which means that all of the int values in the example would be have been autoboxed to cached Integer objects), then the results may have differedsingleton Integer objects and the example code would have operated as intended. Because reference equality and value equality produce the same result only for values within the range of memoized values, and because that range is necessarily limited, successfully using reference equality in place of value equality requires that all values encountered fall within that range. A built-in dependence on "knowledge" of the specific value ranges that may be encountered is unreliable in the face of future changes to the code.

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

Exceptions

EXP03-EX1: The values of autoboxed Boolean variables can may be compared using relational operators, however, if instantiated as an object this is counterproductivethe reference equality operators, because the Java language guarantees that the autoboxing yields either Boolean.True or Boolean.False (as appropriate); these objects are guaranteed to be singletons.

Code Block
bgColor#FFCCCC#CCCCFF
Boolean b1 = new Boolean("true"); true; // Or Boolean.True
Boolean b2 = new Boolean("true"); true; // Or Boolean.True
if(b1 == b2) {     // neveralways equal
  // ...
}

Use this instead:Note, however, that the constructors for class Boolean return distinct newly instantiated objects. Using the reference equality operators in place of value comparisons will yield unexpected results in this case.

Code Block
bgColor#CCCCFF#FFCCCC
Boolean b1 = new Boolean("true; // Or Boolean.True");
Boolean b2 = new Boolean("true; // Or Boolean.True");
if (b1 == b2) {     // alwaysnever equal
  // ...
}

EXP03-EX2 Use the reference equality operators (== and !=) to compare references.

Risk Assessment

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

Guideline

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

...