Originally posted by Ahmed Yehia:
Two Integers with the value between -128 and 127 are considered true comparing with == operator.
But not always - only if you got those two Integers by calling Integer.valueOf(...) or by autoboxing. (Autoboxing calls Integer.valueOf(...) behind the scenes). If you explicitly create two Integer objects with 'new Integer(...)', then == will return false, even if the value is in the range -128...127.
Note that == checks if two variables point to the same object (it only checks if the references are equal, not if the content of the objects that are referred to are equal). If you explicitly create new Integer objects, then you have two different objects, so == will return false.
So why then does it return true when you get the Integer objects via Integer.valueOf(...) or via autoboxing?
The way this works behind the scenes is this: The method Integer.valueOf(...) maintains a pool of Integer objects, with the values in the range -128...127. If you call Integer.valueOf(...) with a value in the range, then the method returns the corresponding Integer object from the pool instead of creating a new Integer object with the specified value. This is done as an optimization, so that for commonly used values it's not necessary to create new Integer objects.
So if you do this:
then a and b are referring to the exact same Integer object - the one that Integer.valueOf(...) returned from its pool, and therefore a == b returns true.
[ September 25, 2007: Message edited by: Jesper Young ]