Inconsistent behavior on java’s ==

Autoboxing of primitives into objects (as used in your calls to method uses a cache of small values. From the Java Language Specification section 5.1.7:

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.

The discussion part of the spec immediately following that is interesting too. Notably a JVM can cache more values if it wants to – you can’t be sure of the results of doing:

Integer i1 = 129;
Integer i2 = 129;
boolean b = (i1 == i2);

Leave a Comment