When the Java compiler autoboxes a primitive to the wrapper class, what code does it generate behind the scenes? I imagine it calls:
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.
Autoboxing is the process of converting a primitive type data into its corresponding wrapper class object instance. It involves the dynamic allocation of memory and initialization of an object for each primitive. In autoboxing there is no need to explicitly construct an object.
Autoboxing is the process by which a primitive type is automatically encapsulated (boxed) into its equivalent type wrappers whenever an object of the type is needed.
You can use the javap
tool to see for yourself. Compile the following code:
public class AutoboxingTest { public static void main(String []args) { Integer a = 3; int b = a; } }
To compile and disassemble:
javac AutoboxingTest.java javap -c AutoboxingTest
The output is:
Compiled from "AutoboxingTest.java" public class AutoboxingTest extends java.lang.Object{ public AutoboxingTest(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]); Code: 0: iconst_3 1: invokestatic #2; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 4: astore_1 5: aload_1 6: invokevirtual #3; //Method java/lang/Integer.intValue:()I 9: istore_2 10: return }
Thus, as you can see, autoboxing invokes the static method Integer.valueOf()
, and autounboxing invokes intValue()
on the given Integer
object. There's nothing else, really - it's just syntactic sugar.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With