3
System.out.println(Integer.valueOf(5) == Integer.valueOf(5));
System.out.println(Integer.valueOf(500) == Integer.valueOf(500));

The output is

true
false

Why does the first line returns true but the second line returns false? What's the trick here since both are calling valueOf() on Integer class.

OneZero
  • 10,328
  • 11
  • 51
  • 82
  • 3
    this is comparing pointers and not integers. The fact that for 5, it returns the same pointer is just an optimization, an implementation detail. (FYI, I don't know any Java at all, I just [read the documentation](http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html)...) – The Paramagnetic Croissant Oct 28 '14 at 19:49
  • 1
    http://stackoverflow.com/questions/1514910/when-comparing-two-integers-in-java-does-auto-unboxing-occur – Pshemo Oct 28 '14 at 19:49
  • 1
    http://stackoverflow.com/questions/20897020/why-integer-class-caching-values-in-the-range-128-to-127 – khelwood Oct 28 '14 at 19:50
  • http://stackoverflow.com/q/20877086 – Dawood ibn Kareem Oct 28 '14 at 20:01

1 Answers1

4

There's cached instances of low numbered Integer objects but not any of higher valued Integer objects.

If you didn't notice before, you are comparing objects, not ints.

NESPowerGlove
  • 5,411
  • 15
  • 27