+ 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
9 Respuestas
+ 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.
+ 1
Could you share your code?
Something must going wrong.
This one works as expected:
https://code.sololearn.com/clb87qMBxv1R/?ref=app
+ 1
It was a sololearn quiz question on challenge Coding Cat [Mouse searching]
+ 1
See also this. Very interesting
https://stackoverflow.com/questions/1700081/why-is-128-128-false-but-127-127-is-true-when-comparing-integer-wrappers-in-ja
0
https://code.sololearn.com/cuvcvASwJyG3/?ref=app
Coding Cat [Mouse searching]
0
Check this code I have attached that's the question and answer was true
False
I couldn't understand how and why ???
0
Yes, I see 🤔
From 128 on it becomes false. This must be some behavior with this "Integer" wrapper class.
0
Coding Cat [Mouse searching] ok please let me know if u know the reason
0
Soumik thank u so much