How does auto boxing/unboxing work in Java?

When in doubt, check the bytecode:

Integer n = 42;

becomes:

0: bipush        42
2: invokestatic  #16                 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
5: astore_1      

So in actuality, valueOf() is used as opposed to the constructor (and the same goes for the other wrapper classes). This is beneficial since it allows for caching, and doesn’t force the creation of a new object on each boxing operation.

The reverse is the following:

int n = Integer.valueOf(42);

which becomes:

0: bipush        42
2: invokestatic  #16                 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
5: invokevirtual #22                 // Method java/lang/Integer.intValue:()I
8: istore_1      

i.e. intValue() is used (again, it’s analogous for the other wrapper types as well). This is really all auto(un)boxing boils down to.

You can read about boxing and unboxing conversions in JLS §5.1.7 and JLS §5.1.8, respectively.

Leave a Comment