Which of the following will cause a compile-time error?
AList list = new ArrayList();
BList list = new ArrayList();
CList
DList list = new ArrayList();
Correct Answer:
B. List list = new ArrayList();
EXPLANATION
Java does not allow covariance with generics. List<Integer> cannot be assigned to List<Number> because you could add a Double to the latter, breaking type safety.
What is the result of type erasure in Java generics?
AGeneric type information is preserved at runtime
BAll generic type information is removed at compile time, replaced with raw types or bounds
CGeneric types are converted to Object only
DType erasure only applies to wildcards
Correct Answer:
B. All generic type information is removed at compile time, replaced with raw types or bounds
EXPLANATION
Type erasure removes all generic type parameters during compilation. For unbounded types, they're replaced with Object; for bounded types, they're replaced with the upper bound.
Which of the following is a valid generic class declaration in Java?
Apublic class Box { }
Bpublic class Box { }
Cpublic class Box { }
Dpublic class Box { }
Correct Answer:
A. public class Box { }
EXPLANATION
Valid generic class declarations allow multiple type parameters with upper bounds. Option A is syntactically correct. Option C uses invalid 'super' keyword in class declaration. Option D has malformed syntax.
What is the advantage of using generics over raw types in terms of 2024-25 Java standards?
ACompile-time type checking prevents ClassCastException
BEnables code reuse without sacrificing type safety
CImproves API clarity and documentation
DAll of the above
Correct Answer:
D. All of the above
EXPLANATION
Generics provide compile-time safety, code reusability through parameterization, and clearer API contracts. These are essential for modern Java development standards.
How would you define a generic method that works with a pair of objects and returns the first one?
A T getFirst(T first, U second) { return first; }
B T getFirst(T first, T second) { return first; }
Cpublic T getFirst(T first, U second) { return first; }
DBoth A and C
Correct Answer:
D. Both A and C
EXPLANATION
Both A and C define valid generic methods with multiple type parameters. C is more explicit with 'public' modifier, but both are functionally equivalent.
Correct Answer:
A. Producer Extends, Consumer Super
EXPLANATION
PECS (Producer Extends, Consumer Super) is a mnemonic for wildcard bounds: use '? extends' when reading (producing), use '? super' when writing (consuming).
Can you create an instance of generic type parameter directly like: T obj = new T();?
AYes, always possible
BNo, because type information is erased at runtime
CYes, only if T extends Serializable
DOnly with reflection
Correct Answer:
B. No, because type information is erased at runtime
EXPLANATION
Due to type erasure, T is replaced with Object at runtime, and you cannot instantiate Object with new T(). You need reflection or pass Class<T> as parameter.