What is the primary purpose of bounded type parameters in generics?
ATo restrict type arguments to specific types or their subtypes
BTo improve code readability only
CTo increase runtime performance
DTo create multiple inheritance in Java
Correct Answer:
A. To restrict type arguments to specific types or their subtypes
EXPLANATION
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.
What is the output of this generic code?
class Pair {
public void display(K key, V value) {
System.out.println(key + ": " + value);
}
}
Pair p = new Pair();
p.display("Age", 25);
AAge: 25
BCompilation error - type mismatch
CAge: 25.0
DRuntime exception
Correct Answer:
A. Age: 25
EXPLANATION
The generic class Pair with two type parameters K and V correctly accepts String and Integer. The display method prints the key-value pair.
Which of the following is a valid generic method declaration?
Apublic T getValue(T value) { return value; }
Bpublic T getValue(T value) { return value; }
Cpublic getValue(T value) { return value; }
Dpublic getValue(T value) { return value; }
Correct Answer:
A. public T getValue(T value) { return value; }
EXPLANATION
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.