ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
import java.util.*;
public class Main {
    public static void main(String[] args) {
        List<Integer> nums = Arrays.asList(1, 2, 3);
        List<? extends Number> readOnly = nums;
        System.out.println(readOnly.get(0));
    }
}
  1. A. 1
  2. B. Compile-time error: cannot assign List<Integer> to List<? extends Number>
  3. C. Compile-time error: readOnly.get(0) returns an unusable wildcard-typed value
  4. D. Runtime ClassCastException

Correct answer: A. 1

A List<? extends Number> can hold any List whose elements are Number or a subtype, including List<Integer>, so the assignment is fine. Reading from it is always safe (get() returns something guaranteed to be at least a Number), so readOnly.get(0) legally yields 1 (as an Integer, auto-widened/printed as a Number-compatible value).

More OOP with C++ and Java questions

Exams that ask this topic