+ 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

24th Mar 2021, 8:05 PM
Ona Nixon 🇹🇿 👑
Ona Nixon  🇹🇿  👑 - avatar
13 Respuestas
+ 20
24th Mar 2021, 8:49 PM
Avinesh
Avinesh - avatar
+ 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.[6]"
25th Mar 2021, 2:29 AM
Ciro Pellegrino
Ciro Pellegrino - avatar
+ 8
Thank you Avinesh for your Explanations.
24th Mar 2021, 9:03 PM
Ona Nixon 🇹🇿 👑
Ona Nixon  🇹🇿  👑 - avatar
+ 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 ^^
24th Mar 2021, 8:37 PM
visph
visph - avatar
+ 4
Avinesh that's quite weird!
24th Mar 2021, 8:51 PM
visph
visph - avatar
+ 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.
24th Mar 2021, 8:56 PM
Avinesh
Avinesh - avatar
+ 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
24th Mar 2021, 8:59 PM
visph
visph - avatar
+ 3
visph I was about to mention the same 😉
24th Mar 2021, 9:03 PM
Avinesh
Avinesh - avatar
+ 3
This is the first weirdness that I learned about Java.
25th Mar 2021, 11:04 AM
Sonic
Sonic - avatar
+ 3
Unsigned int 0 - 255 Signed int -127 to 127 &&0 (total 255)
25th Mar 2021, 4:34 PM
Sanjay Kamath
Sanjay Kamath - avatar
+ 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
24th Mar 2021, 8:19 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
I believe that Avinesh first answer deserve the best answer mark ;) however, that's your thread and you can decide yourself ;P
24th Mar 2021, 9:16 PM
visph
visph - avatar
0
..
12th Mar 2023, 12:12 PM
Saroj Manisha
Saroj Manisha - avatar