Why we use wrapper class in collections?

Wrapper classes are used in Java Collections because collections can store only objects, not primitive data types. Wrapper classes convert primitive values into objects, allowing them to be stored and processed within collection classes.

Key Points: • Java Collections Framework works only with objects and does not support primitive types directly. • Wrapper classes such as Integer, Double, and Character allow primitive values to be stored in collections. • Generics require reference types, making wrapper classes essential when working with collections. • Java provides Autoboxing and Unboxing to automatically convert between primitives and wrapper objects. • Wrapper classes also provide useful utility methods for conversion, comparison, and parsing.

Example: An ArrayList cannot store int values directly, so Integer objects are used instead.

Code Example:

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

public class Demo {

    public static void main(String[] args) {

        List<Integer> numbers = new ArrayList<>();

numbers.add(100); // Autoboxing

int value = numbers.get(0); // Unboxing

        System.out.println(value);
    }
}

Interview Tip: A concise interview answer is:

"We use wrapper classes in collections because the Java Collections Framework stores only objects, not primitive data types. Wrapper classes such as Integer and Double allow primitive values to be stored in collections, and Java automatically handles conversions through autoboxing and unboxing."