When using == for a primitive and a boxed value, is autoboxing done, or is unboxing done

前端 未结 3 1999
野趣味
野趣味 2020-11-27 04:05

The following code compiles (with Java 8):

Integer i1 = 1000;
int i2 = 1000;
boolean compared = (i1 == i2);

But what does it do?

Un

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 04:15

    Lets do some examples :

    Case -1 :

           public static void main(String[] args) {
                Integer i1 = 1000;
                int i2 = 1000;
                boolean compared = (i1 == i2);
                System.out.println(compared);
            }
    

    Byte code :

    ....
            16: if_icmpne     23 // comparing 2 integers
    ....
    

    Case -2 :

    public static void main(String[] args) {
        Integer i1 = 1000;
        Integer i2 = 1000;
        //int i2 = 1000;
        boolean compared = (i1 == i2);
        System.out.println(compared);
    }
    

    Bytecode :

    ...
         16: if_acmpne     23 // comparing references
    ....
    

    So, in case of comparison of Integer and int with == the Integer is unboxed to an int and then comparison happens.

    In case of comparing 2 Integers, the references of 2 Integers are compared.

提交回复
热议问题