Java autoboxing rules

前端 未结 4 1691
难免孤独
难免孤独 2020-12-09 06:04

I am a java novice and so confused by the following example. Is it okay to think that \"==\" sign will compare the values between Integers and \"autoboxed\" Integer

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-09 06:34

    Unboxing will be happing when arithmetic operators, comparison operators appear.

    eg:

    Integer a = 10;
    a = a+10; //1.unboxing a to int 2.calculate a+10 3.boxing 20 to Integer.
    System.out.print(a > 10); //1.unboxing a to int 2. compare
    

    But when == appear, it depends.

    If boxing type appear on both side, it will compare the reference.But if base type appear on one side, and the other side is a boxing type, the boxing type will unboxing to base type.

    eg:

    Integer a = new Integer(129);
    Integer b = new Integer(129);
    System.out.println(a == b); // compare reference return false
    System.out.println(a == 129); // a will unboxing and compare 129 == 129 return true
    

    PS: In Java.lang.Integer Cache to support the object identity semantics of autoboxing for values between -128 and 127 (inclusive) as required by JLS. See source code

    So:

    Integer a = 127;
    Integer b = 127; //cached, the same as b a==b return ture
    
    Integer c = 129;
    Integer d = 129; // not cached, c==d return false
    

提交回复
热议问题