Autoboxing and Unboxing in Java

Autoboxing is an automatic conversion of a primitive type into its corresponding wrapper class object by the java compiler. For an example, converting an int to an Integer.
Consider the following example:
int i = 10;
Integer j = i;
Here, Integer j expects wrapper class of Integer object, but even though if we assign int value rather than Integer object, the code compiles successfully without any errors. This is because of the compiler itself creates an Integer object from i at runtime, as shown below:
Integer i = Integer.valueOf(i);   // autoboxing
Unboxing is an automatic conversion of a wrapper class object into its corresponding primitive type by the java compiler. For an example, converting an Integer to an int.
Consider the following example:
Integer i = new Integer(10);
int j = i;
Here, int j expects primitive type of int value, but even though if we assign Integer object rather than int value, the code compiles successfully without any errors. This is because of the compiler itself creates a primitive int value from i at runtime, as shown below:
int j = i.intValue();   // unboxing
Thus, java compiler performs Autoboxing and Unboxing at runtime.
Here’s the list of Primitive types with their corresponding Wrapper classes.
Primitive typeWrapper class
doubleDouble
longLong
shortShort
floatFloat
intInteger
charCharacter
booleanBoolean
byteByte

Leave a Reply

Discover more from Start Programming | Step-by-Step Guide

Subscribe now to keep reading and get access to the full archive.

Continue reading