Skip to content

Wrapper Classes & Generics πŸš€ΒΆ

Prerequisites: Java Foundations, Java Classes & Objects

Mentor's Note: Primitives like int are fast, but they aren't Objects. To use them in powerful tools like ArrayLists, we need to "Wrap" them. Generics then ensure we don't accidentally put a "Spoon" into a "Shoe Box"! πŸ’‘


🌟 The Scenario: The Cardboard Box πŸ“¦ΒΆ

Imagine you have a single piece of fruit 🍎.

  • The Primitive: The fruit is raw and loose. It's fast to eat but hard to ship or organize in a large warehouse. πŸ“¦
  • The Wrapper: You put the fruit in a Cardboard Box πŸ“¦. Now it's an "Object." It has labels and can be handled by standard shipping tools. (Autoboxing).
  • The Generics: You label the warehouse section: "APPLES ONLY" 🏷️. Now, workers cannot accidentally put an Onion in your Apple box.
  • The Result: You have organized, safe, and professional storage. βœ…

πŸ“– Concept ExplanationΒΆ

1. Wrapper ClassesΒΆ

Wrapper classes allow us to use primitive types (int, char, double) as objects.

Primitive Wrapper
byte Byte
int Integer
char Character
boolean Boolean
  • Autoboxing: Automatic conversion: Integer myObj = 5; πŸͺ„
  • Unboxing: Reverting back: int i = myObj; πŸͺ„

2. GenericsΒΆ

Generics allow you to create classes, interfaces, and methods that work with Any Type, while checking for errors at Compile Time. πŸ›‘οΈ


🎨 Visual Logic: Type Safety¢

graph LR
    A[Raw List] -- "add 'Hi'" --> B[Accepts Anything ❌]
    A -- "add 10" --> B

    C["Generic List <String>"] -- "add 'Hi'" --> D[Success βœ…]
    C -- "add 10" --> E[Compile Error! πŸ›‘]

    style E fill:#f99

πŸ’» Implementation: The Advanced LabΒΆ

// πŸ›’ Scenario: A Universal Storage Box
// πŸš€ Action: Using T as a placeholder for any type

class Box<T> {
    private T content;

    public void set(T item) { this.content = item; }
    public T get() { return this.content; }
}

public class Main {
    public static void main(String[] args) {
        // πŸ“¦ 1. Create a String Box
        Box<String> nameBox = new Box<>();
        nameBox.set("VishnuDigital");

        // πŸ“¦ 2. Create an Integer Box
        Box<Integer> scoreBox = new Box<>();
        scoreBox.set(100);

        System.out.println("Stored: " + nameBox.get());
    }
}

πŸ“Š Sample Dry Run (Autoboxing)ΒΆ

Instruction What Java Sees Description
Integer n = 10; Integer.valueOf(10) Primitive "wrapped" into Object πŸ“¦
int x = n; n.intValue() Object "unwrapped" into primitive 🍎

πŸ“ˆ Technical AnalysisΒΆ

  • Type Erasure: In Java, Generics are only for the compiler. Once the code is compiled, Java removes the type info (<T>) to stay backward compatible. 🧠
  • Constraints: You cannot use primitives directly in Generics. ArrayList<int> is INVALID; use ArrayList<Integer>.

🎯 Practice Lab πŸ§ͺΒΆ

Task: The Generic Swapper

Task: Write a generic method printValue(T value) that prints whatever value is passed to it, along with its data type. Hint: value.getClass().getName(). πŸ’‘


πŸ’‘ Interview Tip πŸ‘”ΒΆ

"Interviewers love asking: 'What is the benefit of Generics?' Answer: It provides Type Safety at compile time and eliminates the need for manual Type Casting!"


πŸ’‘ Pro Tip: "Before software can be reusable it first has to be usable." - Ralph Johnson


← Back: Algorithms | Next: RegEx & Threads β†’