I wrote the simple code:
public static void main(String[] args) {
Integer i1 = 127;
Integer i2 = 127;
boolean flag1 = i1 == i2;
System.out.println(flag1);
Integer i3 = 128;
Integer i4 = 128;
boolean flag2 = i3 == i4;
System.out.println(flag2);
}
But, strangely, the result is as below:
true
false
Can you guys please explain why the difference occurs?
Integer
s are objects, the ==
operator might "work" (in the sense of what you expect it to do - to compare values) only for numbers between [-128,127]. Look at the JLS - 5.1.7. Boxing Conversion:
If the value p being boxed is
true
,false
, abyte
, or achar
in the range \u0000 to \u007f, or anint
orshort
number between -128 and 127 (inclusive), then letr1
andr2
be the results of any two boxing conversions ofp
. It is always the case thatr1 == r2
.
The values you're comparing are not in the range, the result is evaluated to false
. You should use Integer#equals
instead, or simply use the lovely primitive int
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments