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?
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?
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.