Autoboxing & Unboxing in Java

In Java, autoboxing and unboxing are automatic conversions between primitive data types and their corresponding wrapper classes. These features were introduced in Java 5 to simplify coding when working with collections, generics, and object-oriented programming.

1. What is Autoboxing?

Autoboxing is the automatic conversion of a primitive data type into its corresponding wrapper class by the Java compiler.

Example of Autoboxing

public class AutoboxingExample {
    public static void main(String[] args) {
        int primitiveInt = 10;

        // Autoboxing: int → Integer
        Integer objectInt = primitiveInt;

        System.out.println("Primitive int: " + primitiveInt);
        System.out.println("Autoboxed Integer: " + objectInt);
    }
}

Where Autoboxing is Useful?

import java.util.ArrayList;

public class AutoboxingExample {
    public static <T> void printValue(T value) {
        System.out.println("Value: " + value);
    }
    
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(5); // Autoboxing: int → Integer
        numbers.add(10);
        System.out.println("Numbers List: " + numbers);
        
        printValue(20); // Autoboxing: int → Integer
        printValue(3.14); // Autoboxing: double → Double
    }
}

2. What is Unboxing?

Unboxing is the automatic conversion of a wrapper class object back into its corresponding primitive type.

Example of Unboxing

public class UnboxingExample {
    public static void main(String[] args) {
        Integer objectInt = 20;

        // Unboxing: Integer → int
        int primitiveInt = objectInt;

        System.out.println("Wrapper Integer: " + objectInt);
        System.out.println("Unboxed int: " + primitiveInt);
    }
}

Where Unboxing is Useful?

public class UnboxingExample {
    public static void printSquare(int num) {
        System.out.println("Square: " + (num * num));
    }

    public static void main(String[] args) {
        Integer num1 = 50;
        Integer num2 = 30;

        // Unboxing happens automatically
        int sum = num1 + num2;

        System.out.println("Sum: " + sum);
        
        Integer objNum = 7;
        printSquare(objNum); // Unboxing: Integer → int
    }
}

3. Performance Considerations

While autoboxing and unboxing simplify code, they introduce performance overhead:

4. Summary

Autoboxing & unboxing make Java easier to work with, but understanding when and how they occur helps optimize performance.

Feature Autoboxing Unboxing
Definition Converts primitiveWrapper object Converts Wrapper objectprimitive
When? Assigning a primitive value to a wrapper class Assigning a wrapper object to a primitive type
Benefit Simplifies working with collections, generics Allows seamless arithmetic operations
Downside Consume more memory and implicit conversions may impact efficiency