SCJP Java Generics, Enums, and Autoboxing 4 — Questions and Answers
Question 1: Which of the following correctly declares a bounded wildcard that accepts a List of any type that is a supertype of Integer?
- List<? extends Integer>
- List<? super Integer> (Correct answer)
- List<Integer>
- List<?>
Correct answer: List<? super Integer>
The lower-bounded wildcard `? super Integer` accepts Integer and any of its supertypes (Number, Object).
Question 2: What is the result of unboxing a null Integer reference?
- Returns 0
- Returns Integer.MIN_VALUE
- Throws NullPointerException (Correct answer)
- Throws ClassCastException
Correct answer: Throws NullPointerException
Unboxing a null wrapper object throws a NullPointerException at runtime.
Question 3: Given `enum Planet { MERCURY, VENUS, EARTH; }`, what does `Planet.values()` return?
- A List<Planet> of all constants
- An array Planet[] of all constants (Correct answer)
- A Set<Planet> of all constants
- An Iterator<Planet> over all constants
Correct answer: An array Planet[] of all constants
`values()` is a compiler-generated static method that returns a Planet[] array containing all enum constants.
Question 4: Which statement about generic type erasure is TRUE?
- Generic type info is available at runtime via reflection
- Type parameters are replaced by Object or their bound at compile time (Correct answer)
- Generics generate separate bytecode for each type argument
- Type parameters are stored in the .class file at runtime
Correct answer: Type parameters are replaced by Object or their bound at compile time
Type erasure replaces unbounded type parameters with Object and bounded ones with their upper bound in bytecode.
Question 5: What is printed by: `Integer a = 127; Integer b = 127; System.out.println(a == b);`?
- false
- true (Correct answer)
- Compilation error
- NullPointerException
Correct answer: true
Integer values between -128 and 127 are cached, so autoboxed instances with the same value share the same reference.
Question 6: Which method must all enum types implicitly provide that allows retrieving a constant by its String name?
- fromString(String)
- parse(String)
- valueOf(String) (Correct answer)
- getInstance(String)
Correct answer: valueOf(String)
`valueOf(String)` is a compiler-generated static method that returns the enum constant with the given name, throwing IllegalArgumentException if not found.
Question 7: Which of the following would cause a compile-time error when using generics?
- List<?> list = new ArrayList<String>();
- List<Object> list = new ArrayList<String>(); (Correct answer)
- List<String> list = new ArrayList<>();
- List<? extends Number> list = new ArrayList<Integer>();
Correct answer: List<Object> list = new ArrayList<String>();
`ArrayList<String>` is not a subtype of `List<Object>` because generics are invariant, causing a compile-time error.
Which of the following correctly declares a bounded wildcard that accepts a List of any type that is a supertype of Integer?