Does Java autobox when assigning an int to an Object?

╄→гoц情女王★ 提交于 2019-12-17 16:50:09

问题


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 ob? Because the java language specification has nothing on this case.


回答1:


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

Yes. (Or rather, it will box the int value into an Integer object, and then assign the reference to the variable ob. The fact that the integer value is a literal is irrelevant here, really. It could be a method call returning int, for example.)

Because the java language specification has nothing on this case.

That's not true. I mean, it doesn't explicitly deal with assigning to Object, but it works the same way as normal conversions.

Section 5.1.7 of the specification deals with boxing, which would convert int to Integer... and then assigning an Integer reference to an Object variable is a normal reference conversion.




回答2:


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)


来源:https://stackoverflow.com/questions/15139117/does-java-autobox-when-assigning-an-int-to-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!