The Integer
class has a static cache, that stores 256 special Integer
objects - one for every value between -128 and 127. With that in mind, consider the difference between these three.
new Integer(123);
This (obviously) makes a brand new Integer
object.
Integer.parseInt("123");
This returns an int
primitive value after parsing the String
.
Integer.valueOf("123");
This is more complex than the others. It starts off by parsing the String
. Then, if the value is between -128 and 127, it returns the corresponding object from the static cache. If the value is outside of this range, then it invokes new Integer()
and passes in the value, so that you get a new object.
Now, consider the three expressions in the question.
Integer.valueOf("127")==Integer.valueOf("127");
This returns true, because the Integer
whose value is 127 is retrieved twice from the static cache, and compared to itself. There's only one Integer
object involved, so this returns true
.
Integer.valueOf("128")==Integer.valueOf("128");
This returns false
, because 128 is not in the static cache. So a new Integer
is created for each side of the equality. Since there are two different Integer
objects, and ==
for objects only returns true
if both sides are the exact same object, this is going to be false
.
Integer.parseInt("128")==Integer.valueOf("128");
This is comparing the primitive int
value 128 on the left, with a newly created Integer
object on the right. But because it doesn't make sense to compare an int
to an Integer
, Java will auto-unbox the Integer
before doing the comparison; so you end up comparing an int
to an int
. Since the primitive 128 is equal to itself, this returns true
.
.equals()
, otherwise all bets are off. – Cordovan