Skip to main content
Java Basics
CHAPTER 21 Beginner

Generics in Java

Updated: May 17, 2026
5 min read

# CHAPTER 21

Generics in Java

1. Introduction

Before Generics, Collections stored Object types, requiring unsafe casting. Generics add compile-time type safety, ensuring you put the right type in and get the right type out — eliminating ClassCastException at runtime.

2. Generic Classes

java
123456789101112
public class Box<T> {
    private T content;
    public void set(T content) { this.content = content; }
    public T get() { return content; }
}

Box<String> stringBox = new Box<>();
stringBox.set("Hello");
String value = stringBox.get(); // No casting needed!

Box<Integer> intBox = new Box<>();
intBox.set(42);

3. Generic Methods

java
123456789
public static <T> void printArray(T[] array) {
    for (T element : array) {
        System.out.print(element + " ");
    }
    System.out.println();
}

printArray(new Integer[]{1, 2, 3});
printArray(new String[]{"A", "B", "C"});

4. Bounded Type Parameters

java
12345678
// T must be a Number or subclass of Number
public static <T extends Number> double sum(T a, T b) {
    return a.doubleValue() + b.doubleValue();
}

sum(10, 20);      // Works (Integer extends Number)
sum(3.5, 2.1);    // Works (Double extends Number)
// sum("A", "B"); // ERROR! String doesn't extend Number

5. Wildcards

  • ? — Unknown type
  • ? extends T — Upper bound (read-only)
  • ? super T — Lower bound (write-only)
java
123456789
public static void printList(List<?> list) {
    for (Object item : list) System.out.println(item);
}

public static double sumList(List<? extends Number> list) {
    double sum = 0;
    for (Number n : list) sum += n.doubleValue();
    return sum;
}

6. MCQ Quiz with Answers

Question 1

What problem do Generics solve?

Question 2

<T> is called a:

Question 3

<T extends Number> means:

Question 4

Wildcard ? represents:

Question 5

Can primitive types be used with Generics?

Question 6

List<? super Integer> allows adding:

Question 7

Type erasure means:

Question 8

Box<String> and Box<Integer> at runtime are:

Question 9

PECS stands for:

Question 10

Generic methods can be:

7. Summary

Generics provide compile-time type safety, eliminating unsafe casts. Generic classes and methods use type parameters (<T>). Bounded types restrict what types can be used. Wildcards enable flexible method signatures. Type erasure removes generic info at runtime for backward compatibility.

8. Next Chapter Recommendation

In Chapter 22: File Handling in Java, we'll learn how to read from and write to files.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·