Sample questions
Question 1Easy
What does the wildcard in List<?> mean?
- A raw list with generics turned off
- A list that can hold any mix of types and accepts any
add() - A list of some unknown type; you can read elements as
Object but cannot add (except null) - A list of
Object only
Answer: C. A list of some unknown type; you can read elements as Object but cannot add (except null)
Explanation
List<?> is an unbounded wildcard: it accepts List<String>, List<Integer> and so on, but the element type is unknown to the compiler.
Step-by-step solution
- List<?> means the list has an unknown element type.
- You can read elements as Object but cannot add new elements (except null).
- This prevents adding incorrect types to the list.
- It is not a raw list with generics turned off.
- It is not a list that accepts any mix of types and adds anything.
- The correct answer is: A list of some unknown type; you can read elements as Object but cannot add (except null)
Why the other options are wrong
- A. A raw type is plain List without <>; List<?> is a safe wildcard type with generics still on.
- B. List<?> rejects add() of any element except null, because the element type is unknown.
- D. List<?> can hold a list of any element type; it is not limited to Object.
Tip: Use List<?> when you need to handle lists of unknown types without adding new elements.
Question 2Easy
What is the main benefit of using generics such as List<String> instead of a raw List?
- Generic collections run faster because they store primitives directly
- Generic types are kept at runtime so reflection can read the element type of any object
- Type errors are caught at compile time and explicit casts on retrieval are not needed
- They allow a list to hold both int and String without boxing
Answer: C. Type errors are caught at compile time and explicit casts on retrieval are not needed
Explanation
Generics give compile-time type safety; due to type erasure they add no runtime cost and do not allow primitives as type arguments.
Step-by-step solution
- Generics let the compiler check the element type when items are added.
- Wrong types are rejected at compile time instead of failing at runtime.
- Values taken from a List<String> need no explicit cast.
- So the main benefit is option C.
Why the other options are wrong
- A. Generics do not make code faster; collections still hold objects.
- B. Generic type arguments are erased at runtime, so the element type is not kept.
- D. Generic lists still store boxed objects, so ints are boxed and generics do not avoid boxing.
Tip: Generics move type errors from runtime to compile time and remove casts.
Question 3Easy
In class Cache<K, V>, what are K and V called?
- Wildcards
- Annotations
- Raw types
- Type parameters
Answer: D. Type parameters
Explanation
K and V are type parameters; they are replaced by type arguments such as String and Integer when the class is used.
Step-by-step solution
- K and V define the types of keys and values in the Cache class.
- These types are specified when the class is instantiated.
- They are called type parameters because they parameterize the class's behavior.
- Type parameters allow flexibility in using different data types.
- The correct answer is Type parameters.
Why the other options are wrong
- A. Wildcards are the? symbols such as? extends T, not names given to class type parameters.
- B. Annotations are metadata marked with @, such as @Override, not type variables like K and V.
- C. A raw type is using a generic class without type arguments, like Cache alone, not naming K and V.
Tip: Remember: type parameters are like variables for types in generic classes.
Question 4Easy
What is the output?
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, List<Integer>> m = new HashMap<>();
m.computeIfAbsent("x", k -> new ArrayList<>()).add(4);
m.computeIfAbsent("x", k -> new ArrayList<>()).add(8);
System.out.println(m);
}
}
- {x=[4], x=[8]}
- {x=[4, 8]}
- {x=[8]}
- {x=[4]}
Answer: B. {x=[4, 8]}
Explanation
computeIfAbsent creates the list only the first time; the second call returns the existing list, so both values are added.
Step-by-step solution
- First call to
computeIfAbsent creates list for 'x' and adds 4. - Second call finds existing list for 'x' and adds 8.
- Map now has 'x' with list [4, 8].
System.out.println prints the map as {x=[4, 8]}.- Final answer is
{x=[4, 8]}.
Why the other options are wrong
- A. A map has one entry per key, so x appears once, and its list is reused rather than replaced.
- C. The list is not replaced; computeIfAbsent finds the existing list and adds 8 to it.
- D. The second add(8) changes the same list, so 8 is also in it.
Tip: Remember computeIfAbsent adds to existing list or creates new one.
Question 5Medium
What is the output?
import java.util.*;
public class Main {
public static void main(String[] args) {
Object[] arr = new String[2];
arr[0] = "ok";
arr[1] = 42;
System.out.println(arr[0]);
}
}
- ClassCastException is thrown
- Compilation error
- ArrayStoreException is thrown
- ok
Answer: C. ArrayStoreException is thrown
Explanation
Array covariance lets a String[] be referenced as Object[], but the JVM checks each store and rejects an Integer at runtime.
Step-by-step solution
- Arr is typed Object[] but the real array object is a String[].
- arr[0] =
ok stores a String, which is valid. - arr[1] = 42 stores an Integer into the String[]; the JVM checks each store.
- That check throws ArrayStoreException, which is option C.
Why the other options are wrong
- A. A failed array store throws ArrayStoreException, not ClassCastException.
- B. The code compiles, since Object[] accepts any object reference at compile time.
- D. The exception happens before the println, so ok is never printed.
Tip: Array stores are checked at runtime; generic collections are checked at compile time.
Question 6Medium
Which of these is NOT allowed for a type parameter T inside a generic class?
List<T> fieldT[] arr parameter in a methodT as a method return typenew T()
Answer: D. new T()
Explanation
Because T is erased at runtime, the JVM would not know which constructor to call, so new T() does not compile.
Step-by-step solution
- A field of type List<T> is an ordinary generic use and is allowed.
- T as a parameter type, a T[] parameter and a T return type are all allowed.
- New T() is not allowed because T is erased and the JVM cannot know which class to create.
- So the one not allowed is new T(), which is option D.
Why the other options are wrong
- A. A List<T> field is a normal use of a type parameter.
- B. Declaring a T[] parameter is allowed; only creating a generic array with new is not.
- C. A method may return T; that is an ordinary use of a type parameter.
Tip: You cannot create an instance or array of a type variable with new because of erasure.
Question 7Medium
What does type erasure mean in Java generics?
- The compiler checks generic types and then removes them, replacing type parameters with their bounds (or Object) and inserting casts
- The JVM deletes generic objects when they are no longer referenced
- Wildcards are replaced with the most specific subtype at runtime
- Generic type information is stored in every object header at runtime
Answer: A. The compiler checks generic types and then removes them, replacing type parameters with their bounds (or Object) and inserting casts
Explanation
Erasure keeps bytecode compatible with pre-generics code; this is why new T() and instanceof List<String> are not allowed.
Step-by-step solution
- Type erasure removes generic type info at compile time.
- Compiler replaces type parameters with bounds or Object.
- This ensures compatibility with older Java versions.
- Casts are inserted where needed for safety.
- Runtime has no knowledge of generic types.
- Final answer: The compiler checks generic types and then removes them, replacing type parameters with their bounds (or Object) and inserting casts.
Why the other options are wrong
- B. That describes garbage collection, not type erasure; erasure happens at compile time to type parameters.
- C. Erasure replaces wildcards and type parameters with their bounds or Object, not the most specific subtype.
- D. Erasure removes generic type arguments, so objects do not keep them at runtime.
Tip: Remember: Generics are erased at runtime, so you can't check or cast generic types during execution.
Question 8Medium
What is the output?
import java.util.*;
import java.util.function.*;
import java.util.stream.*;
public class Main {
static <T> String show(T t) {
return t.getClass().getSimpleName();
}
public static void main(String[] args) {
System.out.println(show(5) + " " + show("x") + " " + show(2.5));
}
}
- Integer String Double
- int String double
- T T T
- Object Object Object
Answer: A. Integer String Double
Explanation
T is inferred per call; primitives are autoboxed, so the runtime classes are Integer, String and Double.
Step-by-step solution
- show(5) returns Integer because 5 is autoboxed to Integer.
- show("x") returns String because "x" is a String literal.
- show(2.5) returns Double because 2.5 is autoboxed to Double.
- Concatenating these gives Integer String Double.
- Final output is Integer String Double.
Why the other options are wrong
- B. show is generic, so T is always a reference type; 5 is boxed to Integer, not int.
- C. getSimpleName gives the runtime class name of the boxed value, not the type parameter name T.
- D. getClass() returns the actual runtime class, so each name is its own class, not Object.
Tip: Remember autoboxing converts primitives to their wrapper classes in Java.
Question 9Hard
Which line causes a compilation error?
import java.util.*;
public class Main<T> {
T value; // line A
static T shared; // line B
T get() { return value; } // line C
public static void main(String[] args) {
System.out.println(new Main<String>().get()); // line D
}
}
- Line D
- Line B
- Line C
- Line A
Answer: B. Line B
Explanation
A class type parameter belongs to instances; it cannot be used in a static field because statics are shared across all parameterizations.
Step-by-step solution
- Static fields must belong to the class, not its type parameters.
- Type parameters like T are instance-specific and cannot be used in static contexts.
- Line B declares a static field using T, which is invalid because T is not tied to the class itself.
- The error occurs at line B as it tries to use a type parameter in a static context.
- Final answer: Line B.
Why the other options are wrong
- A. Line D calls get() on a Main<String>, which returns String and compiles fine.
- C. Line C returns the instance field value of type T, which is legal in an instance method.
- D. Line A declares an instance field of type T, which is allowed because each instance has its own type.
Tip: Static fields cannot use type parameters; they must be concrete types.
Question 10Hard
Why does Object[] arr = new String[2]; arr[0] = 1; compile, while List<Object> list = new ArrayList<String>(); does not?
- Arrays are covariant and checked at runtime (ArrayStoreException), while generics are invariant and checked at compile time
- Both are covariant; the List line fails only because of the diamond operator
- Arrays are invariant but generics are covariant
- Arrays of String are automatically converted to arrays of Object
Answer: A. Arrays are covariant and checked at runtime (ArrayStoreException), while generics are invariant and checked at compile time
Explanation
The array assignment compiles but throws ArrayStoreException when storing an Integer; generics reject the unsafe assignment up front.
Step-by-step solution
- Arrays are covariant and checked at runtime (ArrayStoreException), while generics are invariant and checked at compile time.
- The array assignment compiles but throws ArrayStoreException when storing an Integer; generics reject the unsafe assignment up front.
Why the other options are wrong
- B. Generic types are invariant, so List<Object> cannot take an ArrayList<String> whatever the diamond is.
- C. It is reversed: arrays are covariant, and generics are invariant.
- D. No conversion happens; the String[] keeps its type and only the static type is Object.
Tip: Remember: Arrays are covariant and checked at runtime, generics are invariant and checked at compile time.
Practise all 22 questions free
The full question bank with timed practice, progress tracking and Vidya, your AI tutor. Free, no ads.
Open this topic in the app →