Govt. Exams
Entrance Exams
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.
class Pair {
public void display(K key, V value) {
System.out.println(key + ": " + value);
}
}
Pair p = new Pair();
p.display("Age", 25);
The generic class Pair with two type parameters K and V correctly accepts String and Integer. The display method prints the key-value pair.
The correct syntax for a generic method is: access_modifier <T> returnType methodName(T parameter). The type parameter <T> must come before the return type.
List list = new ArrayList();
list.add("Java");
System.out.println(list.get(0).length());
"Java" has 4 characters. The generic type ensures the element is a String, so .length() method is available without casting.