PGoCareerGoCareer prep tools
Home
LoginSign up
  • Java
  • Python
  • AI
  • React
  • Angular
  • PHP
  • Node.js
  • SQL
  • DSA
  • HTML
  • CSS
  • JS
  • Spring
  • ML
  • MongoDB

Java · Theory

Java Generics

← All stacks

Theory

226/270

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.

Exam tip

Show List<String> vs raw List. Say compiler catches the wrong add.

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.

Short notes

  • DefGenerics = type-safe collections. List<String> only holds String.
  • RuleAlways write the type parameter. Avoid raw List.
  • RememberType erasure at runtime. Compiler checks at compile time.
  • TrapRaw types + later ClassCastException.

Questions

1

Why generics?

2

What is type erasure?

Previous← Working of HashSet in JavaNextJava Annotations →
P

GoCareerGo

Utilities · Preparation Hub · Resume · CV · Tools — one workspace.

Workspace

DashboardProfilePreparation HubResume builderCV builderCareer planning

PDF Tools

Merge PDFSplit PDFCompress PDFImage to PDFAll toolsJobs

Image & QR

Compress ImageResize ImageQR ScannerQR GeneratorBlogIT interview prep

Company

FAQFeedbackContactPrivacyTermsSitemap

© 2026 GoCareerGo. Keep moving forward.