Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What code does the compiler generate for autoboxing?

When the Java compiler autoboxes a primitive to the wrapper class, what code does it generate behind the scenes? I imagine it calls:

  • The valueOf() method on the wrapper
  • The wrapper's constructor
  • Some other magic?
like image 528
Craig P. Motlin Avatar asked Jan 03 '09 05:01

Craig P. Motlin


People also ask

What is Autoboxing in programming?

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.

Does Autoboxing create a new object?

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.

What is Autoboxing in Java w3schools?

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.


1 Answers

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.

like image 185
Adam Rosenfield Avatar answered Oct 02 '22 03:10

Adam Rosenfield