Java Generics — Java Technical Interview Questions & Answers
Java Generics
Java Generics
- Generics keep types safe: List<String> can only hold String. Without them, a raw List can mix Integer and String and crash later when you cast.
- Write List<String> names = new ArrayList<>();. The compiler checks add. At runtime, generics are mostly erased (type erasure) — don’t expect new T() easily.
- Use them on collections always. Don’t ignore the compiler warning for raw types.
- Let's take this on the board with one tiny Main class — no extra files. Java Generics — output: Asha. Box<String> holds only String — generics catch wrong types at compile time. Start from main, go line by line, and stop at each print. That output is the proof for Generics.
Technical Interview Tip: Show List<String> vs raw List. Say compiler catches the wrong add.
Code Examples for Java Generics
Example
class Box<T> {
T value;
Box(T value) { this.value = value; }
}
public class Main {
public static void main(String[] args) {
Box<String> b = new Box<>("Asha");
System.out.println(b.value);
}
}Java Generics — output: Asha. Box<String> holds only String — generics catch wrong types at compile time.
How to Explain Java Generics to an Interviewer
Why generics?
Type safety List<String> only String
What is type erasure?
Type info mostly removed at runtime