Does Java autobox when assigning an int to an Object?

前端 未结 2 736
臣服心动
臣服心动 2020-12-03 19:30

Is this autoboxing?

Object ob = 8;

Will the above code first wrap the int literal 8 in an Integer and then assign its reference to variable

2条回答
  •  情书的邮戳
    2020-12-03 19:50

    This specific case is detailed in the assignment conversions:

    Assignment conversion occurs when the value of an expression is assigned (§15.26) to a variable: the type of the expression must be converted to the type of the variable.
    Assignment contexts allow the use of one of the following:

    • [...]
    • a boxing conversion optionally followed by a widening reference conversion

    So in your case:

    8 (int) === boxing ===> 8 (Integer) ==== reference widening ===> 8 (Object)
    

提交回复
热议问题