100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

What Are Generics in Java?

What generics are in Java — type erasure, bounded types and compile-time safety — explained with code and interview Q&A.

mediumQ53 of 226 in Object Oriented Programming Est. time: 5 minsLast updated:
Open Code Lab

Expected Interview Answer

Generics let a class, interface, or method be parameterized over types, so the same code works with different data types while the compiler enforces type safety at compile time instead of relying on runtime casts.

Before generics, Java collections stored plain Object references, so retrieving an element required an explicit downcast that could fail at runtime with a ClassCastException. A generic class like `List<T>` lets the compiler know the element type up front, catching type mismatches at compile time and removing the need for casts entirely. Java implements generics via type erasure: generic type information exists only at compile time and is erased to raw types (or bounds) in the compiled bytecode, which is why you cannot create a `new T[]` directly or check `instanceof T` at runtime. Bounded type parameters (`<T extends Number>`) and wildcards (`<? extends T>`, `<? super T>`) extend generics to express constraints and variance.

  • Compile-time type safety instead of runtime ClassCastException
  • Eliminates the need for explicit casting when reading from collections
  • Enables reusable, type-parameterized algorithms and data structures
  • Improves API readability by documenting expected types in signatures

AI Mentor Explanation

A labeled kit bag marked "Bats Only" lets any player reach in and pull out a bat without checking what they grabbed — the label itself is the guarantee, decided once when the bag was packed. An unlabeled generic bag would force every player to look inside and verify before use, exactly like an unchecked cast. A generic type parameter is that label: `KitBag<Bat>` tells the compiler what’s inside up front, so no runtime check is ever needed to trust the contents.

Step-by-Step Explanation

  1. Step 1

    Declare a type parameter

    Use angle brackets, e.g. `class Box<T> { T value; }`, to parameterize the class over a type T.

  2. Step 2

    Instantiate with a concrete type

    Callers write `Box<String>` to fix T to String for that instance.

  3. Step 3

    Compiler enforces type safety

    Reads and writes to T-typed members are checked against String at compile time.

  4. Step 4

    Erasure at bytecode level

    The compiled class has no runtime record of T; bounds/casts are inserted by the compiler instead.

What Interviewer Expects

  • Correct explanation of compile-time type safety vs runtime casting
  • Understanding of type erasure and its practical consequences
  • Ability to write a simple generic class or method
  • Awareness of bounded type parameters and wildcards

Common Mistakes

  • Claiming Java generics exist at runtime (they are erased)
  • Trying to create `new T[]` or `new T()` directly without a workaround
  • Confusing generics with the Object-based pre-Java-5 style collections
  • Not knowing raw types still compile (with warnings) for backward compatibility

Best Answer (HR Friendly)

Generics let you write a class or method once and have it work with any type you specify, while the compiler checks that you’re using the right type everywhere. Instead of storing everything as a generic Object and casting it back later — which can fail at runtime — generics catch type mistakes when you compile, which makes code safer and easier to read.

Code Example

A simple generic class
class Box<T> {
    private T value;
    Box(T value) { this.value = value; }
    T get() { return value; }
    void set(T value) { this.value = value; }
}

Box<String> nameBox = new Box<>("Ada");
String name = nameBox.get(); // no cast needed, compiler knows it’s a String

Box<Integer> ageBox = new Box<>(30);
// ageBox.set("thirty"); // compile-time error, not a runtime one

Follow-up Questions

  • What is type erasure and why does Java use it?
  • Why can you not create a generic array like `new T[10]`?
  • What is a bounded type parameter, e.g. `<T extends Number>`?
  • What is the difference between a raw type and a parameterized type?

MCQ Practice

1. What is the main benefit of generics over using Object and casting?

Generics move type checking to compile time, removing the risk of a runtime ClassCastException.

2. What happens to generic type information at runtime in Java, due to type erasure?

Type erasure removes generic type parameters at compile time, leaving raw types or their bounds in bytecode.

3. Why can you not write `new T[10]` inside a generic class in Java?

Because of erasure, the runtime has no concrete type for T, so array creation with a generic type is disallowed directly.

Flash Cards

Generics in one line?Parameterizing a class, interface, or method over a type for compile-time safety.

How does Java implement generics?Via type erasure — generic info exists only at compile time.

Bounded type parameter example?`<T extends Number>` restricts T to Number or its subtypes.

Main benefit?No explicit casting and compile-time detection of type mismatches.

1 / 4

Continue Learning