Boxed numbers are compared with == or !=, which compare references

tx0/java:boxed-identityrecommendedwarningbug

What it finds

count == limit with two Integer variables compares references: it is true for small values, which Integer.valueOf caches, and false for larger ones with the same value. equals, or comparing the unboxed values, compares the numbers.

Both operands must be known to be of the same box among Integer, Long, Short, Byte, Character, Float and Double; Boolean has only two values that are usually shared. A comparison that is only a shortcut before equals on the same operands is left alone, and so are comparisons in assertions. Code sometimes compares boxes by reference on purpose, as with a sentinel object, so the rule is not in the default tier.

From the rule's source, boxed_identity.rs.

Example from the rule's tests
class Counters {  boolean same(Integer a, Integer b, Long c, int d, Boolean e, Boolean f, Object o) {    boolean r = a == b;tx0 reports: a == b compares the references of two boxed numbers    r = a != b;tx0 reports: a != b compares the references    r = a == d;    r = e == f;    r = a == o;    r = c == null;    return r;  }   static boolean equal(Long x, Long y) {    return x == y || (x != null && x.equals(y));  }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/java:boxed-identity" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/java:boxed-identity] reason="..."

tx0 explain tx0/java:boxed-identity shows the same in the terminal. Found a false positive? Report it.