CodeQL documentation

Reference equality test of boxed types

ID: java/reference-equality-of-boxed-types
Kind: problem
Severity: error
Precision: very-high
Tags:
   - reliability
   - correctness
   - external/cwe/cwe-595
Query suites:
   - java-security-and-quality.qls

Click to see the query in the CodeQL repository

Comparing two boxed primitive values using == or != compares object identity, which may not be intended.

Recommendation

Usually, you should compare non-primitive objects, for example boxed primitive values, by using their equals methods.

Example

With the following definition, the method call refEq(new Integer(2), new Integer(2)) returns false because the objects are not identical.

boolean refEq(Integer i, Integer j) {
	return i == j;
}

With the following definition, the method call realEq(new Integer(2), new Integer(2)) returns true because the objects contain equal values.

boolean realEq(Integer i, Integer j) {
	return i.equals(j);
}

References

  • J. Bloch and N. Gafter, Java Puzzlers: Traps, Pitfalls, and Corner Cases, Puzzle 32. Addison-Wesley, 2005.

  • Java API Documentation: Object.equals(), Integer.equals().

  • Common Weakness Enumeration: CWE-595.