Introduction
This blog discusses a new feature of Java SE 5, namely, Autoboxing and Unboxing. Let us first see the definition of these two features:
Autoboxing: Autoboxing or boxing is the conversion of primitive data types into objects of the corresponding Wrapper class.
Example: Conversion of int to an object of the Integer class.
Unboxing: Unboxing is the opposite of boxing. It involves the conversion of objects of Wrapper classes to their corresponding primitive data types.
Example: Converting an object of Integer class to int.

Autoboxing / Unboxing has several advantages.
- Developers can build cleaner, easier-to-read code by using autoboxing and unpacking.
- We may utilise primitive types and Wrapper class objects thanks to this method interchangeably, eliminating the requirement for explicit typecasting.
Also see, Duck Number in Java and Swap Function in Java
Use Cases
Let us consider a few examples to better understand these data type conversions in Java.
Example of Boxing: Conversion of int and char variables to objects of Integer and Character classes.
Program
class AutoboxingExample
{
public static void main (String[] args)
{
// Create an int data type variable.
int intVar = 10;
// Autoboxing the int variable to create an object of the Integer class with the same value.
Integer intObject = intVar;
System.out.println("Value of int data type variable: " + intVar);
System.out.println("Value of Integer Object " + intObject);
System.out.println();
// Create a char data type variable.
char charVar = 'a';
// Autoboxing the char variable to create an object of the Character class with the same value.
Character charObject = new Character('a');
System.out.println("Value of char data type variable: " + charVar);
System.out.println("Value of Character Object " + charObject);
}
}
Output
Value of int data type variable: 10
Value of Integer Object 10
Value of char data type variable: a
Value of Character Object a
Example of Unboxing: Conversion of an object of Integer and Character class to int and char, respectively.
Program
class UnboxingExample
{
public static void main (String[] args)
{
// Create an object of the Integer class.
Integer intObject = new Integer(5);
// Unboxing the object by equating it to an int data type variable.
int intVar = intObject;
System.out.println("Value of Integer Object " + intObject);
System.out.println("Value of int data type variable: " + intVar);
System.out.println();
// Create an object of the Character class.
Character charObject = new Character('a');
// Unboxing the object by equating it to an char data type variable.
char charVar = charObject;
System.out.println("Value of Character Object " + charObject);
System.out.println("Value of char data type variable: " + charVar);
}
}
Output
Value of Integer Object 5
Value of int data type variable: 5
Value of Character Object a
Value of char data type variable: a