Govt. Exams
Entrance Exams
Advertisement
Topics in Java Programming
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);
class Pair {
public void display(K key, V value) {
System.out.println(key + ": " + value);
}
}
Pair p = new Pair();
p.display("Age", 25);
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?
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.
What will be the output of the following code?
List list = new ArrayList();
list.add("Java");
System.out.println(list.get(0).length());
List list = new ArrayList();
list.add("Java");
System.out.println(list.get(0).length());
Correct Answer:
A. 4
EXPLANATION
"Java" has 4 characters. The generic type ensures the element is a String, so .length() method is available without casting.
Which keyword is used to declare a generic class in Java?
Correct Answer:
A.
EXPLANATION
<T> is the standard syntax for declaring a generic type parameter in Java classes.
What is the primary purpose of Generics in Java?
Correct Answer:
A. To provide type safety and eliminate type casting
EXPLANATION
Generics enable type safety at compile time and eliminate the need for explicit type casting, reducing runtime errors.