Integer == int allowed in java

后端 未结 6 988
自闭症患者
自闭症患者 2020-12-06 07:29

I was wondering if java automatically turns a Integer into an int when comparing to an int? Or will the == try and compare references on primitives?

Is this always t

6条回答
  •  有刺的猬
    2020-12-06 08:15

    Yes, it will unbox. This is covered in section 15.21.1 of the JLS (the numeric == operator):

    If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2). If the promoted type of the operands is int or long, then an integer equality test is performed; if the promoted type is float or double, then a floating-point equality test is performed.

    Note that binary numeric promotion performs value set conversion (§5.1.13) and unboxing conversion (§5.1.8).

    (I've linkified section 5.1.8 as that's what talks about the conversion from Integer to int being available.)

提交回复
热议问题