☕ Java Intermediate

What are generics in Java?

Why Interviewers Ask This

This question targets practical, hands-on experience with Java. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.

Answer

Generics allow classes, interfaces, and methods to operate on types specified as parameters, providing type safety at compile time without requiring casts. Example: List<String> is a list that can only hold Strings — trying to add an Integer would be a compile error. Before generics (Java 1.4), collections held Object references requiring explicit casts everywhere and causing runtime ClassCastException. Generic methods: public <T> T getFirst(List<T> list). Bounded type parameters: <T extends Comparable<T>> restricts T to types that are comparable. Due to type erasure, generic type information is removed at compile time — at runtime, List<String> is just List.

Pro Tip

If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.