SCJP Java Generics, Enums, and Autoboxing 2 — Questions and Answers
Question 1: What does a wildcard `?` represent in Java generics?
- Any unknown type (Correct answer)
- The Object class specifically
- A null type
- An optional type parameter
Correct answer: Any unknown type
The wildcard `?` in generics represents an unknown type, used when you don't know or care about the specific type argument.
Question 2: What is the difference between `List<? extends Number>` and `List<? super Number>` in Java?
- They are identical
- extends is for reading (producer); super is for writing (consumer) (Correct answer)
- super is for reading; extends is for writing
- extends allows any type; super allows no type
Correct answer: extends is for reading (producer); super is for writing (consumer)
The PECS principle: `<? extends T>` (Producer Extends) is used for reading elements; `<? super T>` (Consumer Super) is used for writing elements.
Question 3: Which enum method returns the name of the enum constant as a String?
- toString() only
- name() (Correct answer)
- label()
- getValue()
Correct answer: name()
The `name()` method returns the exact name of the enum constant as declared in the source code.
Question 4: Can Java enums have constructors?
- No, enums cannot have constructors
- Yes, but only public constructors
- Yes, but enum constructors are always private (Correct answer)
- Yes, but only static constructors
Correct answer: Yes, but enum constructors are always private
Enum constructors are always `private` (implicitly or explicitly) because enum constants are created by the JVM, not by external code.
Question 5: What happens when you compare two Integer wrapper objects with `==` in Java?
- Always compares their numeric values
- Compares object references, not values (except for cached range -128 to 127) (Correct answer)
- Always returns true if values are equal
- Throws an exception
Correct answer: Compares object references, not values (except for cached range -128 to 127)
`==` on Integer objects compares references; however, Integer caches values from -128 to 127, so `==` may return true for small values due to the shared cache.
Question 6: Which of the following is a valid use of a bounded type parameter in Java generics?
- <T extends String, Integer>
- <T extends Comparable<T>> (Correct answer)
- <T super Object>
- <T implements Serializable>
Correct answer: <T extends Comparable<T>>
`<T extends Comparable<T>>` bounds T to types that implement Comparable, enabling comparison operations within the generic code.
What does a wildcard `?` represent in Java generics?