Generics Questions with Answers

22 practice questions on Generics (Core Java) with answers and step-by-step solutions. Try 10 samples below, then practise all 22 free in the AptiNest app.

Sample questions

Question 1Easy

What does the wildcard in List<?> mean?

  1. A raw list with generics turned off
  2. A list that can hold any mix of types and accepts any add()
  3. A list of some unknown type; you can read elements as Object but cannot add (except null)
  4. 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

  1. List<?> means the list has an unknown element type.
  2. You can read elements as Object but cannot add new elements (except null).
  3. This prevents adding incorrect types to the list.
  4. It is not a raw list with generics turned off.
  5. It is not a list that accepts any mix of types and adds anything.
  6. 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?

  1. Generic collections run faster because they store primitives directly
  2. Generic types are kept at runtime so reflection can read the element type of any object
  3. Type errors are caught at compile time and explicit casts on retrieval are not needed
  4. 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

  1. Generics let the compiler check the element type when items are added.
  2. Wrong types are rejected at compile time instead of failing at runtime.
  3. Values taken from a List<String> need no explicit cast.
  4. 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?

  1. Wildcards
  2. Annotations
  3. Raw types
  4. 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

  1. K and V define the types of keys and values in the Cache class.
  2. These types are specified when the class is instantiated.
  3. They are called type parameters because they parameterize the class's behavior.
  4. Type parameters allow flexibility in using different data types.
  5. 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);
    }
}
  1. {x=[4], x=[8]}
  2. {x=[4, 8]}
  3. {x=[8]}
  4. {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

  1. First call to computeIfAbsent creates list for 'x' and adds 4.
  2. Second call finds existing list for 'x' and adds 8.
  3. Map now has 'x' with list [4, 8].
  4. System.out.println prints the map as {x=[4, 8]}.
  5. 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]);
    }
}
  1. ClassCastException is thrown
  2. Compilation error
  3. ArrayStoreException is thrown
  4. 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

  1. Arr is typed Object[] but the real array object is a String[].
  2. arr[0] = ok stores a String, which is valid.
  3. arr[1] = 42 stores an Integer into the String[]; the JVM checks each store.
  4. 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?

  1. List<T> field
  2. T[] arr parameter in a method
  3. T as a method return type
  4. new 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

  1. A field of type List<T> is an ordinary generic use and is allowed.
  2. T as a parameter type, a T[] parameter and a T return type are all allowed.
  3. New T() is not allowed because T is erased and the JVM cannot know which class to create.
  4. 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?

  1. The compiler checks generic types and then removes them, replacing type parameters with their bounds (or Object) and inserting casts
  2. The JVM deletes generic objects when they are no longer referenced
  3. Wildcards are replaced with the most specific subtype at runtime
  4. 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

  1. Type erasure removes generic type info at compile time.
  2. Compiler replaces type parameters with bounds or Object.
  3. This ensures compatibility with older Java versions.
  4. Casts are inserted where needed for safety.
  5. Runtime has no knowledge of generic types.
  6. 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));
    }
}
  1. Integer String Double
  2. int String double
  3. T T T
  4. 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

  1. show(5) returns Integer because 5 is autoboxed to Integer.
  2. show("x") returns String because "x" is a String literal.
  3. show(2.5) returns Double because 2.5 is autoboxed to Double.
  4. Concatenating these gives Integer String Double.
  5. 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
    }
}
  1. Line D
  2. Line B
  3. Line C
  4. 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

  1. Static fields must belong to the class, not its type parameters.
  2. Type parameters like T are instance-specific and cannot be used in static contexts.
  3. Line B declares a static field using T, which is invalid because T is not tied to the class itself.
  4. The error occurs at line B as it tries to use a type parameter in a static context.
  5. 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?

  1. Arrays are covariant and checked at runtime (ArrayStoreException), while generics are invariant and checked at compile time
  2. Both are covariant; the List line fails only because of the diamond operator
  3. Arrays are invariant but generics are covariant
  4. 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

  1. Arrays are covariant and checked at runtime (ArrayStoreException), while generics are invariant and checked at compile time.
  2. 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 →

Related topics

See all Core Java topics · All topics