R
Rishtaara
Java Fundamentals
Lesson 32 of 36Article18 min

Wrapper Classes, Generics & Annotations

Integer, Double, Boolean wrap primitives for collections and null support.

Wrapper Classes — primitives as objects

Integer, Double, Boolean wrap primitives for collections and null support.

Autoboxing converts int → Integer automatically. Unboxing goes back.

Real-life example: Wrapper is putting a small gem (int) in a gift box (Integer) so it fits on a shelf that only holds boxes.

Wrappers and autoboxing
Integer num = 42;        // autoboxing
int value = num;         // unboxing

List<Integer> scores = new ArrayList<>();
scores.add(90);          // int boxed to Integer

System.out.println(Integer.parseInt("100"));

Generics — type-safe collections

Generics <T> let classes and methods work with any type while keeping compile-time checks.

List<String> cannot accidentally hold integers.

Real-life example: Generics are labeled boxes — "Strings only" sticker stops you from putting screws inside.

Generic class
class Box<T> {
    private T value;
    Box(T value) { this.value = value; }
    T get() { return value; }
}

Box<String> nameBox = new Box<>("Asha");
Box<Integer> ageBox = new Box<>(20);

Annotations — metadata in code

@Override, @Deprecated, @SuppressWarnings are built-in. Frameworks use @Test, @Entity, etc.

Annotations do not change logic by themselves — tools read them at compile or runtime.

Real-life example: Annotations are sticky labels on luggage — "Fragile", "This side up" — handlers know what to do.

Common annotations
class Parent {
    void greet() {}
}

class Child extends Parent {
    @Override
    void greet() {
        System.out.println("Hello");
    }

    @Deprecated
    void oldMethod() {}
}