Autoboxing and unboxing are the automatic conversions from a primitive type to an instance of its corresponding wrapper class, and vice versa. For example, converting int to Integer is autoboxing, and converting Integer to int is unboxing. These conversions are handled by the Java compiler.

Autoboxing

Autoboxing is triggered mainly in two scenarios: assignment and method invocation.

Assignment When a primitive value is assigned to its corresponding wrapper class, autoboxing automatically converts the primitive value into an object of the wrapper class.

Integer num = 9; // autoboxing: int 9 to Integer 9

Method invocation When a primitive value is passed as a parameter to a method that expects a wrapper class object, the compiler automatically handles the conversion. The primitive value will be assigned to a wrapper class type variable. Internally, the compiler employs the valueOf (take Integer class as example) method to automatically box primitives into appropriate wrapper objects.

Unboxing

Unboxing is the reverse process where the compiler automatically converts a wrapper class object back into its corresponding primitive type. This allows wrapper class objects to be used in contexts where a primitive is required. Similarly, it can happen in assignment and method invocation. Here we use assignment as example.

Assignment

Integer num = 9;
int primitiveNum = num; // unboxing: Integer 9 to int 9

Method invocation

public class UnboxingExample {
    public static void main(String[] args) {
        Integer num = 5;
        printInt(num); // unboxing: Integer 5 to int 5
    }
    
    public static void printInt(int value) {
        System.out.println(value);
    }
}
 

Usage in Java collections

Autoboxing and unboxing are used extensively in Java collections framework, since only wrapper types are accepted in Java collections. Here is an example with ArrayList.

import java.util.ArrayList;
 
public class AutoboxingUnboxingExample {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList<>();
        list.add(5); // autoboxing: int to Integer
        
        // using unboxing to get a value from the collection
        int value = list.get(0); // unboxing: Integer to int
    }
}

Back to parent page: Java Standard Edition (Java SE) and Java Programming

Web_and_App_DevelopmentProgramming_LanguagesJavaAutoboxingUnboxingJava_Collections_FrameworkWrapper_Class

Reference: