Integer i1=127; Integer i2=127; System.out.println(i1==i2); i1=128; i2=128; System.out.println(i1==i2);
i found this in a challenge , why is answer -> true false
You can find the answer here. https://code.sololearn.com/cn2vMn0Uyr74/?ref=app
only 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."
Thank you Avinesh for your Explanations.
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 ^^
Avinesh that's quite weird!
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
visph I was about to mention the same 😉
This is the first weirdness that I learned about Java.
Unsigned int 0 - 255 Signed int -127 to 127 &&0 (total 255)
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