Govt. Exams
Entrance Exams
Generics provide compile-time safety, code reusability through parameterization, and clearer API contracts. These are essential for modern Java development standards.
List list = new ArrayList();
list.add(10);
Object obj = list.get(0);
System.out.println(obj.getClass().getName());
Although obj is declared as Object, it holds an Integer instance. getClass() returns the actual runtime type, which is Integer.
This causes a compilation error due to type mismatch. List<Integer> cannot hold ArrayList<String>. Generics do not support implicit type conversion.
Bounded type parameters like <T extends Number> restrict the types that can be passed as type arguments, ensuring type safety and enabling access to specific methods.
Type parameters in Java must be declared before the return type using angle brackets. Option A has correct syntax: <T> comes before return type void.
The interface has two type parameters: K and V, making it a generic interface that can be implemented with different type combinations.
ArrayList list = new ArrayList();
list.add("Java");
Object obj = list.get(0);
String str = (String) obj;
System.out.println(str.length());
The code compiles and runs correctly. 'Java' has 4 characters. The explicit cast is necessary because get() returns Object type.
Generics only work with reference types. 'int' is a primitive type, so 'Integer' wrapper class must be used instead.
Generics provide compile-time type checking, preventing ClassCastException and eliminating the need for explicit casting at runtime.
The wildcard '?' in generics represents an unknown type, allowing flexibility when the exact type is not known or not important.