Compare 2 Integer numbers, strange behavior

Dat Nguyen

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?

Maroun

Integers 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, a byte, or a char in the range \u0000 to \u007f, or an int or short number between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == 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.

edited at
0

Comments

0 comments
Login to comment

Related

compare angle and up in strange behavior

Strange behavior when comparing numbers

How to compare the digits of 2 integer numbers in c (without arrays and strings)

Strange behavior of String.Compare with OrdinalIgnoreCase

Comparing Integer values in Java, strange behavior

php multiply strange integer overflow behavior

Strange behavior with String.to_integer/1

Lodash set integer paths strange behavior

MySQL strange behavior with comma separated list of numbers

Labwindows strange behavior when adding DOUBLE numbers

Jest issue very strange case : compare numbers

ASM Compare 2 Numbers

Unexpected behavior of dcast with integer64 numbers

Python compare integer number with hexadecimal and binary numbers

Compare two integer and count matching numbers

Strange typescript / angular2 import behavior

Select2 strange behavior with objects

Strange cv2 behavior with imshow

Strange behavior with PHP's str_pad() and numbers

Strange behavior when finding range of values between two numbers

Strange behavior of Regular Expression matching numbers in Python 3

Compare if 2 input numbers are in range of 2 columns

Unable to compare 2 integer variables in batch file

Strange behavior when appending to a 2d slice

SDL2 / SDL Image strange PNG behavior with RGB values

Strange behavior with function that converts a vector2 to an angle in degrees

Strange behavior when submitting post request in Angular 2

Strange behavior when appending to 2d slice of strings

Java Slick2d rectangle collision detection strange behavior