Entrance Exams
Govt. Exams
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.
The bound 'T extends Comparable<T>' ensures T is comparable to itself, enabling type-safe comparison operations.
Generics only work with reference types. 'int' is a primitive type, so 'Integer' wrapper class must be used instead.
PECS guides when to use upper bounds (? extends) for producers/readers and lower bounds (? super) for consumers/writers.
All three allow storing multiple types because they use unbounded or Object-level wildcards, though List<?> is most restrictive for additions.
Lower-bounded wildcards (? super T) allow superclasses of T. This assignment is valid because ArrayList<Number> fits '? super Integer'.
Upper-bounded wildcards (? extends T) are used for reading data. Adding elements is unsafe because the compiler doesn't know the exact type.
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.
Option A uses proper diamond syntax with matching type parameters on both sides. Options B, C produce unchecked warnings, and Option D is invalid due to invariance.