How to properly compare two Integers in Java?

前端 未结 10 1370
情歌与酒
情歌与酒 2020-11-21 07:06

I know that if you compare a boxed primitive Integer with a constant such as:

Integer a = 4;
if (a < 5)

a will automaticall

10条回答
  •  终归单人心
    2020-11-21 07:46

    We should always go for equals() method for comparison for two integers.Its the recommended practice.

    If we compare two integers using == that would work for certain range of integer values (Integer from -128 to 127) due to JVM's internal optimisation.

    Please see examples:

    Case 1:

    Integer a = 100; Integer b = 100;

    if (a == b) {
        System.out.println("a and b are equal");
    } else {
       System.out.println("a and b are not equal");
    }
    

    In above case JVM uses value of a and b from cached pool and return the same object instance(therefore memory address) of integer object and we get both are equal.Its an optimisation JVM does for certain range values.

    Case 2: In this case, a and b are not equal because it does not come with the range from -128 to 127.

    Integer a = 220; Integer b = 220;

    if (a == b) {
        System.out.println("a and b are equal");
    } else {
       System.out.println("a and b are not equal");
    }
    

    Proper way:

    Integer a = 200;             
    Integer b = 200;  
    System.out.println("a == b? " + a.equals(b)); // true
    

    I hope this helps.

提交回复
热议问题