Java introduced Autoboxing and Unboxing in Java 5 to facilitate the automatic conversion between primitive data types and their corresponding wrapper classes. This feature simplifies data manipulation by eliminating the need for explicit conversion.
What is Autoboxing?
- Definition: Autoboxing is the automatic conversion of a primitive data type into its corresponding wrapper class object.
- Example: Converting an
intto anInteger.
Syntax Example:
int num = 50;
Integer obj = num; // Autoboxing: int → IntegerCode language: JavaScript (javascript)
What is Unboxing?
- Definition: Unboxing is the automatic conversion of a wrapper class object to its corresponding primitive data type.
- Example: Converting an
Integerto anint.
Integer obj = 100;
int num = obj; // Unboxing: Integer → intCode language: JavaScript (javascript)
Autoboxing and Unboxing Example Program
import java.util.ArrayList;
public class AutoboxingUnboxingDemo {
public static void main(String[] args) {
// Autoboxing: Primitive to Wrapper
int a = 5;
Integer intObj = a; // int to Integer
System.out.println("Autoboxed Integer: " + intObj);
// Unboxing: Wrapper to Primitive
Integer b = 10;
int primitiveInt = b; // Integer to int
System.out.println("Unboxed int: " + primitiveInt);
// Autoboxing in Collections
ArrayList<Double> doubleList = new ArrayList<>();
doubleList.add(4.5); // Autoboxing: double to Double
doubleList.add(7.8);
doubleList.add(3.14);
System.out.println("Autoboxed Double List: " + doubleList);
// Unboxing in Collections
double sum = 0;
for (Double value : doubleList) {
sum += value; // Unboxing: Double to double
}
System.out.println("Sum of Double List: " + sum);
// Autoboxing in Expressions
Integer x = 100;
Integer y = 200;
Integer z = x + y; // Autoboxing and Unboxing in Expression
System.out.println("Sum of x and y: " + z);
}
}
/*
Autoboxed Integer: 5
Unboxed int: 10
Autoboxed Double List: [4.5, 7.8, 3.14]
Sum of Double List: 15.44
Sum of x and y: 300
*/Autoboxing and unboxing simplify the conversion between primitive data types and their wrapper classes, making Java code more readable and concise. However, developers should be aware of potential performance overheads and the risk of NullPointerException during unboxing.
