Home Subjects Java Programming Generics

Java Programming
Generics

Java OOP, collections, multithreading

25 Q 10 Topics Take Mock Test
Advertisement
Difficulty: All Easy Medium Hard 21–25 of 25
Topics in Java Programming
Q.21 Easy Generics
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);
A Age: 25
B Compilation error - type mismatch
C Age: 25.0
D Runtime 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.

Test
Q.22 Easy Generics
Which of the following is a valid generic method declaration?
A public T getValue(T value) { return value; }
B public T getValue(T value) { return value; }
C public getValue(T value) { return value; }
D public 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.

Test
Q.23 Easy Generics
What will be the output of the following code?
List list = new ArrayList();
list.add("Java");
System.out.println(list.get(0).length());
A 4
B 5
C Compilation error
D Runtime exception
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.

Test
Q.24 Easy Generics
Which keyword is used to declare a generic class in Java?
A
B generic
C template
D type
Correct Answer:  A.
EXPLANATION

<T> is the standard syntax for declaring a generic type parameter in Java classes.

Test
Q.25 Easy Generics
What is the primary purpose of Generics in Java?
A To provide type safety and eliminate type casting
B To increase memory allocation
C To reduce code compilation time
D To automatically manage garbage collection
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.

Test
IGET
IGET AI
Online · Exam prep assistant
Hi! 👋 I'm your iget AI assistant.

Ask me anything about exam prep, MCQ solutions, study tips, or strategies! 🎯
UPSC strategy SSC CGL syllabus Improve aptitude NEET Biology tips