Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 1 of 10 · Java Generics & Type Safety
Interview question

What are Generics in Java and why were they introduced? Java में Generics क्या हैं और इन्हें क्यों introduce किया गया?

Answer

Generics allow classes, interfaces, and methods to operate on a type specified at compile time, providing compile-time type safety and eliminating the need for manual casting.

// BEFORE generics (Java 1.4 and earlier) - raw types, unsafe
List list = new ArrayList();
list.add('Hello');
list.add(42);  // no compile-time check - mixing types allowed

String s = (String) list.get(0);  // manual cast required
String s2 = (String) list.get(1);  // ClassCastException at RUNTIME! 42 isn't a String

// WITH generics (Java 5+) - type-safe
List<String> typedList = new ArrayList<>();
typedList.add('Hello');
// typedList.add(42);  // COMPILE ERROR - caught immediately, not at runtime

String value = typedList.get(0);  // no cast needed, compiler knows the type
BenefitExplanation
Compile-time type checkingType errors caught before running the program
No explicit castingCompiler inserts casts automatically and safely
Generic algorithmsWrite one method that works for multiple types

Generics classes, interfaces, methods को compile time पर specified type पर operate करने देते हैं, compile-time type safety देते हैं और manual casting की ज़रूरत खत्म करते हैं।

// Generics से पहले (Java 1.4) - raw types, unsafe
List list = new ArrayList();
list.add('Hello');
list.add(42);  // कोई compile-time check नहीं

String s = (String) list.get(0);
String s2 = (String) list.get(1);  // ClassCastException runtime पर!

// Generics के साथ (Java 5+) - type-safe
List<String> typedList = new ArrayList<>();
typedList.add('Hello');
// typedList.add(42);  // COMPILE ERROR - तुरंत पकड़ा जाता है

String value = typedList.get(0);  // cast की ज़रूरत नहीं
फायदाविवरण
Compile-time type checkingErrors program चलने से पहले पकड़े जाते हैं
Explicit casting नहींCompiler automatically cast करता है

Was this answer clear?