Why
Integer.valueOf(1000) == Integer.valueOf(1000)
returns false
, while
Integer.valueOf(6) == Integer.valueOf(6)
returns true
?
From the documentation:
This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.
Therefore, Integer.valueOf(6)
has only one instance object while Integer.valueOf(1000)
creates a new Integer
.
Hence Integer.valueOf(6) == Integer.valueOf(6)
and Integer.valueOf(1000) != Integer.valueOf(1000)
Because some lower valued Integer objects are cached and reused. So all Integer objects of lower values, like 6, refer to the same Integer instance.