Question 1
What is the result of compiling the following program? ```java import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List<? extends Number> nums = new ArrayList<Integer>(); nums.add(1); System.out.println(nums.size()); } } ```
A. An exception is thrown at runtime
Assumes the failure happens at runtime, but the compiler rejects the add before the program can run, so the method is never reached.
B. Compilation failsCorrect answer
Correct. An upper-bounded wildcard (? extends Number) makes the list read-only for elements: the compiler only knows it holds some subtype of Number, so it cannot prove adding an Integer is type-safe and rejects the call (JLS 8 §4.5.1).
C. It compiles because 1 is a Number
The value being a Number is not enough: the compiler cannot know the list's actual element type is Integer — it might be a List<Double> — so it forbids the add rather than trusting the value.
D. 1
This would be the printed size only if the code compiled and ran; the add is rejected at compile time, so nothing is printed.
Explanation
An upper-bounded wildcard makes the list read-only for elements: the compiler only knows it holds some unknown subtype of Number, so it cannot prove that adding an Integer is safe. You can read Numbers out of such a list, but the only value you may add is null, so the add call is rejected at compile time.