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?

+3


source to share


1 answer


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

, a byte

, or char

in the range \ u0000 to \ u007f or number int

, or short

between -128 and 127 (inclusive), then let them r1

, and r2

- the results of any two conversion boxes p

. It always happens that r1 == 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

.

+7


source







All Articles