Govt. Exams
Entrance Exams
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.
<T> is the standard syntax for declaring a generic type parameter in Java classes.
Generics enable type safety at compile time and eliminate the need for explicit type casting, reducing runtime errors.