Integer i1=127; Integer i2=127; System.out.println(i1==i2); i1=128; i2=128; System.out.println(i1==i2);
12 Answers
New Answer3/24/2021 8:05:19 PM
Ona Nixon πΉπΏ π12 Answers
New Answeronly integers between -128 and 127 are object interning so for 127 their wrappers point to the same object. 128 is out of this range, so two distinct objects are generated. If you compare the objects then they are different, but if you compare the values ββwith equals() then they are equals. https://en.m.wikipedia.org/wiki/String_interning "Objects other than strings can be interned. For example, in Java, when primitive values are boxed into a wrapper object, certain values (any boolean, any byte, any char from 0 to 127, and any short or int between β128 and 127) are interned, and any two boxing conversions of one of these values are guaranteed to result in the same object.[6]"
Rik Wittkopp I don't think, as if one variable is assigned a long instead of an int, then the other will be too assigned a long ^^
visph I know but that is how it works and I created that demo code some time back when I had the same doubt.
Avinesh I understand that's how it works, but I'm surprised and I am good with JS wich has a reputation of weird in how it handle some things, but it is not so when you know how that work... I just realized that it is not alone :D
I believe it may be that at 128, the number is no longer an integer but a long, so the comparison of integer = 128 is false. This is my theory only
I believe that Avinesh first answer deserve the best answer mark ;) however, that's your thread and you can decide yourself ;P
Sololearn Inc.
535 Mission Street, Suite 1591Send us a message