-4

I recently come across a strange question in java and could not figure out how it is working. Please help me.

(Integer)100 == (Integer)100  works by returning true
(Integer)200 == (Integer)200  doesn't works returns false why?
SMA
  • 36,381
  • 8
  • 49
  • 73
Saravana Kumar M
  • 460
  • 9
  • 19
  • So what's the question again? Better provide what you thought the output would be and what the output was before you are downvoted as the tolerance for such questions on SO is very low. – Chetan Kinger Feb 27 '15 at 11:05
  • What exactly is the question? This is not an executable java code. – Uwe Allner Feb 27 '15 at 11:06
  • I don't think it is working. put it in `if((Integer)100 == (Integer)100 (Integer)200 == (Integer)200)` . compilation error ... you need `*` – Cataclysm Feb 27 '15 at 11:08

1 Answers1

4

Reason why (Integer)100 == (Integer)100 works is Integer class uses IntegerCache which maintains cache values from -128 to 127. So if you type cast 100, it will get you the same object again and again and hence two reference of Integer would be same.

Now for (Integer)200 == (Integer)200 Since it's out of range of values maintained in cache, you get a new object every time and hence reference are not the same which you are trying to compare with "==".

When you type case an integer primitive to wrapper, internally call gets router to valueOf method and details of the same is mentioned here.

SMA
  • 36,381
  • 8
  • 49
  • 73