What are generics in Java?
Java generics, introduced in Java 5, allow classes, interfaces, and methods to be parameterized by type. Instead of writing a container that holds Object and requires manual casting, you declare List<String>, and the compiler enforces that only String values are added and returns String values without explicit casts. This moves type errors from runtime ClassCastException to compile-time errors, significantly improving code safety and clarity.
Generic classes are declared with a type parameter: class Box<T> { private T value; }. Generic methods declare their type parameter before the return type: public <T> T identity(T value). Type parameters are conventionally named T (type), E (element), K (key), V (value), R (return type).
Bounded type parameters constrain the valid type arguments. <T extends Comparable<T>> requires T to implement Comparable, enabling comparisons within the generic method. <T extends Number> restricts T to Number subclasses.
Wildcards add flexibility when consuming generic types without writing generic methods. List<?> accepts a list of any type (useful when only reading, via the upper-bounded principle). List<? extends Number> accepts List<Integer>, List<Double> etc. — you can read from it safely but not write (since the concrete type is unknown). List<? super Integer> accepts List<Integer>, List<Number>, List<Object> — you can write Integer into it but reading yields only Object.
The PECS mnemonic (Producer Extends, Consumer Super) governs wildcard selection: use ? extends T when the list produces values you read; use ? super T when the list consumes values you write.
Generics are a compile-time mechanism only. The type parameters are erased from bytecode at runtime (type erasure) — List<String> and List<Integer> are both just List at the JVM level. This is why you cannot write new T() or new T[] directly, perform instanceof checks like obj instanceof List<String>, or overload methods that differ only in generic parameter.
Explains compile-time type safety, basic generic class/method syntax, and upper-bounded wildcards with extends.
Covers PECS rule with accurate explanation, type erasure and its practical constraints, bounded type parameters, and the difference between wildcards in usage position vs. type parameter declarations.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment