What are Generics in Java?
Understand generics in Java: type parameters, compile-time type safety, type erasure, bounded types, and wildcards, with clear code examples and interview tips.
Expected Interview Answer
Generics let you write classes, interfaces, and methods that work with a type parameter supplied later, giving you compile-time type safety and eliminating manual casts, as in List<String> where the compiler guarantees only Strings go in and come out.
Introduced in Java 5, generics move type errors from runtime to compile time by parameterizing types with placeholders like <T>. The compiler enforces the type and then applies type erasure, removing the parameter in bytecode for backward compatibility. Bounded types (<T extends Number>) and wildcards (<? extends T>, <? super T>) control how flexible a generic API can be.
- Compile-time type checking catches errors early
- Removes explicit casts and ClassCastException risk
- Enables reusable, type-safe classes and methods
- Improves readability by documenting intended types
- Powers the Collections framework cleanly
AI Mentor Explanation
Generics are like a labeled kit bag that only accepts a specific team's gear — mark it 'India' and the manager stops any wrong jersey going in at packing time, not during the match. You avoid discovering a mismatched kit at the crease when it is too late to fix.
Step-by-Step Explanation
Step 1
Declare a type parameter
Add a placeholder like <T> to a class, interface, or method signature to represent a type chosen by the caller.
Step 2
Use the parameter
Reference T inside fields, arguments, and return types so the compiler tracks a single consistent type throughout.
Step 3
Instantiate with a real type
Supply the concrete type at use, such as new Box<String>(), letting the diamond operator infer it where possible.
Step 4
Bound when needed
Constrain the parameter with <T extends Number> so the code can safely call methods available on the bound.
Step 5
Apply wildcards
Use <? extends T> for read-only producers and <? super T> for consumers to make APIs flexible yet safe.
What Interviewer Expects
- Generics provide compile-time type safety
- They remove explicit casts and ClassCastException risk
- Understanding of type parameters like <T>
- Awareness of type erasure and its consequences
- Knowledge of bounded types and wildcards (extends/super)
Common Mistakes
- Thinking generics exist at runtime (ignoring type erasure)
- Confusing <? extends T> with <? super T>
- Trying to create a generic array like new T[]
- Using raw types such as List instead of List<String>
- Believing generics improve runtime performance
Best Answer (HR Friendly)
“Generics let you tell Java exactly what type a container or method should handle, like saying a list holds only text. The compiler then blocks wrong types early, so you get fewer surprises and don't have to keep converting values yourself.”
Code Example
import java.util.*;
// A simple generic container
class Box<T> {
private T value;
public void set(T value) { this.value = value; }
public T get() { return value; }
}
public class GenericsDemo {
// Bounded type parameter: T must be a Number
static <T extends Number> double sum(List<T> nums) {
double total = 0;
for (T n : nums) total += n.doubleValue();
return total;
}
// Wildcard: read from any list of Numbers or subtypes
static void printAll(List<? extends Number> list) {
for (Number n : list) System.out.println(n);
}
public static void main(String[] args) {
Box<String> box = new Box<>(); // diamond operator infers String
box.set("hello");
String s = box.get(); // no cast needed
System.out.println(s);
System.out.println(sum(List.of(1, 2, 3)));
printAll(List.of(1.5, 2.5));
}
}Follow-up Questions
- What is type erasure and why does Java use it?
- What is the difference between <? extends T> and <? super T>?
- Why can't you create an array of a generic type?
- What are bounded type parameters?
- How do generics differ from using Object and casting?
MCQ Practice
1. What is the main benefit of Java generics?
Generics let the compiler enforce types and remove explicit casts; they do not speed up runtime.
2. What does type erasure mean?
The compiler removes generic type information after checking it, so it is not present at runtime.
3. Which wildcard is best for a method that only reads elements?
<? extends T> makes a producer that you can safely read from, following the PECS rule.
Flash Cards
What do generics provide? — Compile-time type safety and elimination of manual casts via type parameters like <T>.
What is type erasure? — Generic type information is removed during compilation, so it does not exist at runtime.
PECS rule? — Producer Extends, Consumer Super: use <? extends T> to read, <? super T> to write.
Can you write new T[]? — No — you cannot create arrays of a generic type because of erasure; use collections instead.