Can you explain the difference between unboxing and autoboxing in Java?

Autoboxing and unboxing are features introduced in Java that automatically convert between primitive data types and their corresponding wrapper classes. These conversions simplify coding and make it easier to work with collections and generics.

Key Points: • Autoboxing automatically converts a primitive value into its corresponding wrapper object. • Unboxing automatically converts a wrapper object back into its primitive value. • These features reduce manual conversion code and improve readability. • Autoboxing and unboxing are commonly used when working with Collections Framework and Generics. • Wrapper classes involved include Integer, Double, Boolean, Character, and others.

Example: When adding an int value to an ArrayList<Integer>, Java automatically converts the int to an Integer object through autoboxing. When retrieving the value, Java converts it back to int through unboxing.

Code Example:

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

public class Demo {

    public static void main(String[] args) {

Integer number = 100; // Autoboxing

int value = number; // Unboxing

        System.out.println(value);
    }
}

Quick Comparison:

Autoboxing: • Primitive → Wrapper Object • int → Integer • Automatic object creation

Unboxing: • Wrapper Object → Primitive • Integer → int • Automatic value extraction

Interview Tip: A concise interview answer is:

"Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class, while unboxing is the automatic conversion of a wrapper object back to its primitive type. These features simplify working with collections and generic classes in Java."