+ 3

# integer comparison

How integer i1=127,integer i2=127;System.out.print(i1==i2); integeri2=128;integeri1=128; System.out.print(i1==i2); gives true false

24th Apr 2021, 1:57 PM
alagammai uma
+ 3
When you store a number Integer i1 = 127, it is to stored in a place similar to the String Constant Pool (SCP). Since 127 already exists on the heap, when you compare i1 and i2, the values are compared and it returns true. This is the same for all values from -128 to 127. When you store a value greater than 127 or less than -128, a new object is created on the heap. This is also known as auto boxing . So, when you compare i1 and i2 after assigning 128 to each, the memory address of each object on the heap is compared and they clearly aren't the same. So it returns false. The point to remember here is that, in the first case no new objects are created whereas in the second case, objects ARE created.
24th Apr 2021, 2:44 PM
Soumik
+ 1
Could you share your code? Something must going wrong. This one works as expected: https://code.sololearn.com/clb87qMBxv1R/?ref=app
24th Apr 2021, 2:19 PM
Coding Cat
+ 1
It was a sololearn quiz question on challenge Coding Cat [Mouse searching]
24th Apr 2021, 2:22 PM
alagammai uma
0
https://code.sololearn.com/cuvcvASwJyG3/?ref=app Coding Cat [Mouse searching]
24th Apr 2021, 2:32 PM
alagammai uma
0
Check this code I have attached that's the question and answer was true False I couldn't understand how and why ???
24th Apr 2021, 2:33 PM
alagammai uma
0
Yes, I see ðŸ¤” From 128 on it becomes false. This must be some behavior with this "Integer" wrapper class.
24th Apr 2021, 2:42 PM
Coding Cat
0
Coding Cat [Mouse searching] ok please let me know if u know the reason
24th Apr 2021, 2:43 PM
alagammai uma
0
Soumik thank u so much
24th Apr 2021, 2:45 PM
alagammai uma