0

Why

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

returns false, while

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

returns true?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
fatCop
  • 2,556
  • 10
  • 35
  • 57

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
  • 52,687
  • 11
  • 83
  • 118
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,496
  • 17
  • 28