Skip to main content
InterviewHubPRO
Section Overview
Q14

Question 14 of 50

Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)

28%
Java Core & JVM (50 Qs)•Part 2: Advanced Concurrency, Memory & Modern Java Architecture (11 - 24)

How does Type Erasure work in Java Generics and what are its runtime implications?

senior LevelCode ExampleTypeScriptSystem Design

In Simple Words: Type Erasure is the mechanism where the Java compiler enforces type constraints at compile time, but removes (erases) all generic type information when emitting bytecode (.class file). At runtime, generic types like List<String> and List<Integer> are identical: both are simply the raw type List.

Why Type Erasure Exists:

To maintain backward compatibility with legacy Java 1.4 codebases when generics were introduced in Java 5 (2004).

Runtime Limitations Caused by Erasure:

  1. Cannot instantiate generic types directly: new T() is illegal.
  2. Cannot create generic arrays: new T[10] is illegal.
  3. Cannot use primitive types in generics: List<int> is invalid (must use wrapper List<Integer>).
  4. Cannot check instanceof List<String> (only instanceof List<?> is allowed).
java
// What you write in Java:
List<String> names = new ArrayList<>();
names.add("Alice");
String first = names.get(0);

// What bytecode actually executes (decompiled equivalent):
List names = new ArrayList();
names.add("Alice");
String first = (String) names.get(0); // Compiler injects automatic cast