Skip to main content Skip to docs navigation
TechSpiderTutorials

Java Autoboxing and Unboxing

Java is a language that heavily relies on both primitive types (such as int, char, double, etc.) and their corresponding wrapper classes (like Integer, Character, Double, etc.). To bridge the gap between these two types, Java provides autoboxing and unboxing, which automate the conversion process. This feature simplifies code and reduces the need for manual type conversion.

What is Autoboxing?

Autoboxing is the automatic conversion that the Java compiler makes between primitive types and their corresponding wrapper classes. It allows you to use primitive types and wrapper classes interchangeably without explicitly converting between them.

For example, when you assign an int to an Integer, the compiler automatically performs the conversion:

int primitiveInt = 10;
Integer wrapperInt = primitiveInt;  // Autoboxing: int to Integer

What is Unboxing?

Unboxing is the reverse process of autoboxing. It refers to the automatic conversion from a wrapper class to its corresponding primitive type. This happens when a wrapper class is used in a context where a primitive type is expected.

For example, when you assign an Integer to an int, the compiler automatically performs the conversion:

Integer wrapperInt = 10;
int primitiveInt = wrapperInt;  // Unboxing: Integer to int

Benefits of Autoboxing and Unboxing

  1. Code Simplicity: Autoboxing and unboxing reduce the need for explicit type conversions, making code cleaner and more readable.
  2. Consistency: These features enable seamless interactions between primitive types and collections (e.g., List<Integer>), which otherwise only work with objects.
  3. Less Error-Prone: Automated conversions help prevent common errors associated with manual type conversions.

autoboxing-unboxing-example

1: Using Autoboxing in Collections

import java.util.ArrayList;
import java.util.List;

public class AutoboxingExample {
    public static void main(String[] args) {
        List numbers = new ArrayList<>();

        // Autoboxing: primitive int to Integer
        numbers.add(5);
        numbers.add(10);

        // Print the list
        for (Integer number : numbers) {
            System.out.println(number);
        }
    }
}

Example 2: Autoboxing and Unboxing in Method Calls

public class AutoboxingUnboxingMethodExample {
    public static void main(String[] args) {
        printNumber(20);  // Autoboxing: int to Integer
    }

    public static void printNumber(Integer number) {
        System.out.println(number);
    }
}

Example 3: Performing Arithmetic Operations

public class ArithmeticAutoboxingUnboxing {
    public static void main(String[] args) {
        Integer a = 10;
        Integer b = 20;

        // Unboxing happens here for arithmetic operation
        int sum = a + b;  // Unboxing Integer to int

        System.out.println("Sum: " + sum);
    }
}