Wrapper Classes, Autoboxing & Unboxing

🟡 Intermediate Level | Java Core Syntax

📖 Definition

Wrapper Classes (Integer, Double, Boolean, Character, etc.) wrap primitive data types inside object wrappers, allowing primitives to be used in object-based frameworks like the Java Collections Framework. Autoboxing is the automatic conversion of primitives into wrapper objects, and Unboxing is the reverse.

🌐 Multilingual Explanations

English

Wrapper classes wrap primitives into Heap objects. Autoboxing converts `int` -> `Integer` automatically. Unboxing converts `Integer` -> `int` automatically.

Hindi

Wrapper classes primitives ko Object banati hain taaki unhe Collections mein use kiya ja sake. Autoboxing primitive ko object mein convert karti hai.

Marathi

Wrapper classes primitive data types la Objects madhye convert kartat.

Hinglish

Autoboxing: `Integer num = 5;` (primitive auto-converted to Object). Unboxing: `int val = num;` (Object auto-converted back to primitive).

⚡ Code Example

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

public class WrapperDemo {
    public static void main(String[] args) {
        // 1. Autoboxing: Primitive int 50 automatically converted to Integer object
        Integer obj = 50;

        // 2. Unboxing: Integer object automatically converted to primitive int
        int num = obj;

        // 3. String Parsing Utility Methods
        int parsedInt = Integer.parseInt("123");
        double parsedDouble = Double.parseDouble("45.67");

        // 4. Using Wrappers in Collections
        List list = new ArrayList<>();
        list.add(100); // Autoboxing inside ArrayList

        System.out.println("Parsed: " + parsedInt + ", Max Int: " + Integer.MAX_VALUE);
    }
}

⚠️ Common Pitfalls

NullPointerException during Unboxing: Unboxing a `null` wrapper object reference (e.g. Integer val = null; int num = val;) throws a runtime NullPointerException.

🎯 Tiered Practice Exercises

  1. Beginner: Parse the string "250" into an integer using Integer.parseInt().
  2. Intermediate: Demonstrate autoboxing inside an ArrayList<Double> collection.
  3. Advanced: Explain the performance impact of frequent autoboxing/unboxing inside heavy computation loops.

🧭 Navigation

← 02. Type Casting | Module Hub | Module Index →