 Integer i1=127; Integer i2=127; System.out.println(i1==i2); i1=128; i2=128; System.out.println(i1==i2); | Sololearn: Learn to code for FREE!

+27

# 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

+20

You can find the answer here. https://code.sololearn.com/cn2vMn0Uyr74/?ref=app

+11

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."

+8

Thank you Avinesh for your Explanations.

+5

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 ^^

+4

Avinesh that's quite weird!

+3

visph I know but that is how it works and I created that demo code some time back when I had the same doubt.

+3

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

+3

visph I was about to mention the same 😉

+3

This is the first weirdness that I learned about Java.

+3

Unsigned int 0 - 255 Signed int -127 to 127 &&0 (total 255)

+2

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

+1