Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java autobox when assigning an int to an Object?

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.

like image 333
PrashanD Avatar asked Feb 28 '13 15:02

PrashanD


People also ask

What happens when an int is Autoboxed?

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

Do arrays autobox?

Arrays are never autoboxes or auto-unboxed, e.g. if you have an array of integers int[] x , and try to put its address into a variable of type Integer[] , the compiler will not allow your program to compile. Autoboxing and unboxing also has a measurable performance impact.

Are int and Integer interchangeable in Java?

In Java, int is a primitive data type while Integer is a Wrapper class. int, being a primitive data type has got less flexibility. We can only store the binary value of an integer in it. Since Integer is a wrapper class for int data type, it gives us more flexibility in storing, converting and manipulating an int data.


2 Answers

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.

like image 109
Jon Skeet Avatar answered Nov 15 '22 04:11

Jon Skeet


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)
like image 36
assylias Avatar answered Nov 15 '22 04:11

assylias