Course contentsShow
← Java
Lesson 902 of 2,87021. Generics FundamentalsFree lesson

Type Safety: Compile-Time vs Runtime

How generics provide compile-time type checking and prevent ClassCastException at runtime.

Type Safety: Compile-Time vs Runtime

What you'll learn: How generics catch type errors before your program runs, preventing crashes that would otherwise happen during execution.

The Problem Without Generics

Before generics, collections stored everything as Object, forcing you to cast retrieved items. If you accidentally cast to the wrong type, your program would compile fine but crash at runtime with a ClassCastException. This is runtime type safety — errors only appear when the code executes.

ArrayList list = new ArrayList(); // raw type
list.add("Hello");
list.add(42);
String s = (String) list.get(1); // Compiles, crashes at runtime!

Generics: Catching Errors Early

Generics shift type checking from runtime to compile-time. When you declare ArrayList<String>, the compiler enforces that only String objects can be added. If you try to add an Integer, the code won't even compile.

ArrayList<String> list = new ArrayList<>();
list.add("Hello");
// list.add(42); // Compiler error: incompatible types!
String s = list.get(0); // No cast needed, guaranteed safe

Why This Matters

Compile-time type safety means:

  • Errors are caught immediately while writing code
  • No ClassCastException surprises in production
  • No manual casts required — the compiler knows the type
  • Your IDE can provide better autocomplete and refactoring

Think of it like spell-check versus publishing a book with typos. Generics are the spell-check that catches mistakes before your program ships.

Type Erasure Reminder

Remember from type erasure: at runtime, ArrayList<String> and ArrayList<Integer> both become just ArrayList. The type parameter information is gone. But that's okay — the compiler already verified everything was correct, so runtime checks aren't needed.

Key Takeaway: Generics provide compile-time type safety, transforming runtime ClassCastException errors into compile-time errors you can fix immediately, with no casting required.