Compare 2 Integer numbers, strange behavior
I wrote a 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, oddly enough, the result is as follows:
true
false
Can you guys explain the reason for the difference?
source to share
Integer
s are objects, the operator ==
can "work" (in the sense of what you would expect from it) to compare values) only for numbers between [-128,127]. Have a look at JLS - 5.1.7. Boxing conversion :
If p is equal to the value in the box
true
,false
, abyte
, orchar
in the range \ u0000 to \ u007f or numberint
, orshort
between -128 and 127 (inclusive), then let themr1
, andr2
- the results of any two conversion boxesp
. It always happens thatr1 == r2
.
The values you are comparing are out of range, the result is evaluated as false
. You should use Integer#equals
or just use a lovely primitive int
.
source to share