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
4/24/2021 1:57:17 PM
alagammai uma
9 Answers
New AnswerWhen 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.
Could you share your code? Something must going wrong. This one works as expected: https://code.sololearn.com/clb87qMBxv1R/?ref=app
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
Check this code I have attached that's the question and answer was true False I couldn't understand how and why ???
Yes, I see 🤔 From 128 on it becomes false. This must be some behavior with this "Integer" wrapper class.