Are Java Integers always == when they're .equals()?
No. In the normal case, you cannot rely on ==
with Integer
instances when attempting a numeric value comparison. For that you must either unbox them to int
before comparing, or use equals
.
What you're seeing in your example is the fact that the JDK caches and reuses a limited number of Integer
instances (for Integers
representing -128 to 127). From Integer.valueOf(int)
:
This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
Now, your code is using boxing conversions rather than Integer.valueOf
, and the specification doesn't say that boxing conversions use Integer.valueOf
, and yet it's likely that that's exactly what they do (in effect; e.g., that both the boxing conversion and Integer.valueOf
use the same underlying mechanism and cache).
You can see that ==
is not reliable for Integer
instances if you use a different value: (live copy)
Integer x = 524; // <==== Changed
Integer y = x + 1;
Integer z = y - 1;
System.out.println("equals? " + x.equals(z));
System.out.println("==? " + (x == z));
Output (probably, and it's what I get on IDEOne, but again the docs say Integer
may cache other values):
equals? true
==? false