Autoboxing
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.
When you assign a primitive value to a reference of the corresponding wrapper class, autoboxing automatically converts the primitive value into an object of the wrapper class.
int intValue = 10;
Integer integerValue = intValue; // Autoboxing
Autoboxing in Method Invocation : Autoboxing occurs when passing primitive values to methods that expect wrapper class objects as arguments.
void printInteger(Integer value) {
System.out.println(value);
}
int intValue = 20;
printInteger(intValue); // Autoboxing
Autoboxing in Collections : Autoboxing is commonly used in collections, where primitive values are automatically converted to wrapper objects when adding elements to collections that hold objects.
List<Integer> numbers = new ArrayList<>();
numbers.add(30); // Autoboxing
While autoboxing provides convenience, it’s essential to be mindful of its performance implications. Autoboxing involves the creation of additional objects, which can impact performance, especially in performance-critical sections of code.
Unboxing
Auto Unboxing is the process where a wrapper object is converted to its corresponding primitive value. It is the reverse process of autoboxing.
Unboxing to Primitive Type : When you assign a wrapper class object to a primitive type variable, unboxing automatically extracts the primitive value from the wrapper object.
Integer integerValue = 10;
int intValue = integerValue; // Unboxing
Unboxing in Method Invocation : Unboxing also occurs when passing wrapper class objects to methods that expect primitive types as arguments.
void printInt(int value) {
System.out.println(value);
}
Integer integerValue = 20;
printInt(integerValue); // Unboxing
Unboxing from Collections : Unboxing is commonly used when retrieving primitive values from collections that hold wrapper object
List<Integer> numbers = new ArrayList<>();
numbers.add(30);
int value = numbers.get(0); // Unboxing