Since Java 1.5, some of the wrapper classes have introduced a cache. For Integer
, any number between -128 and 127 inclusive fell in the cache. Other values needed to be wrapped in a new Integer
every time.
The ==
operator compares references. Since the cached Integer values for 127 are in fact the very same object, ==
returns true
. For the 128 Integer
objects, they are two different objects and do not have the same reference equality.
There are two more reliable ways you can compare for equality:
if (treti.equals(ctvrty)) { /* do something */ }
or:
if (treti.compareTo(ctvrty) == 0) { /* do something */ }
The latter comparison takes advantage of the fact that Integer
implements the Comparable
interface and thus defines a compareTo
method which returns a negative value if the first object is "less than" the second, a positive value if the first object is "greater than" the second, and zero if the objects compare equal.