0

Why

Integer.valueOf(1000) == Integer.valueOf(1000)

returns false, while

Integer.valueOf(6) == Integer.valueOf(6)

returns true?

Pshemo
  • 118,400
  • 24
  • 176
  • 257
fatCop
  • 2,406
  • 10
  • 33
  • 56

2 Answers2

3

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)

Jean Logeart
  • 50,693
  • 11
  • 81
  • 116
1

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.

NESPowerGlove
  • 5,456
  • 16
  • 27