SCJP Java Generics, Enums, and Autoboxing 5 — Questions and Answers
Question 1: An enum constant can have a body with an abstract method override. What must the enum declaration itself contain for this to compile?
- The abstract method must be declared abstract in the enum body (Correct answer)
- The enum must implement an interface
- The enum must extend an abstract class
- Abstract methods are not allowed in enums at all
Correct answer: The abstract method must be declared abstract in the enum body
When a constant overrides a method with its own body, the enum must declare that method as abstract so each constant provides an implementation.
Question 2: What does `Collections.unmodifiableList(list)` return when passed a `List<String>`, in terms of generics?
- List<Object>
- List<String> (Correct answer)
- List<?>
- List<? extends String>
Correct answer: List<String>
`unmodifiableList` is generic and preserves the type parameter, returning `List<String>` when given a `List<String>`.
Question 3: What is the result of: `Integer x = 200; Integer y = 200; System.out.println(x == y);`?
- true
- false (Correct answer)
- Compilation error
- Depends on the JVM vendor
Correct answer: false
Values outside the -128 to 127 cache range create new Integer objects, so == compares references and returns false.
Question 4: Which of the following is a valid way to restrict a generic method to only accept subtypes of Number?
- <T> void method(T t)
- <T super Number> void method(T t)
- <T extends Number> void method(T t) (Correct answer)
- <? extends Number> void method(Number n)
Correct answer: <T extends Number> void method(T t)
`<T extends Number>` is a bounded type parameter that restricts T to Number and its subclasses.
Question 5: Which enum method returns the zero-based position of a constant in its declaration order?
- position()
- index()
- ordinal() (Correct answer)
- rank()
Correct answer: ordinal()
`ordinal()` returns the ordinal (zero-based declaration position) of the enum constant.
Question 6: Given `List<Integer> list = new ArrayList<>(); list.add(5);`, which call demonstrates autoboxing?
- list.get(0)
- list.size()
- list.add(5) (Correct answer)
- list.clear()
Correct answer: list.add(5)
`list.add(5)` autoboxes the int literal 5 into an Integer object before adding it to the List<Integer>.
Question 7: What happens when you attempt to create a generic array like `T[] arr = new T[10];` inside a generic class?
- It compiles and works correctly
- It produces a compile-time error (Correct answer)
- It compiles but throws ArrayStoreException at runtime
- It compiles with an unchecked warning and may cause ClassCastException
Correct answer: It produces a compile-time error
Creating a generic array with `new T[10]` is a compile-time error because the type T is not known due to erasure.
An enum constant can have a body with an abstract method override.
What must the enum declaration itself contain for this to compile?