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));
}
}- A. 1
- B. Compile-time error: cannot assign List<Integer> to List<? extends Number>
- C. Compile-time error: readOnly.get(0) returns an unusable wildcard-typed value
- 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
- What is printed? java public class Main { static void risky(int x) throws Exception { if (x < 0) throw new Exception("neg")…
- What is printed? java public class Main { static String f(int x) { try { if (x == 0) throw new ArithmeticException("div0"); return "ok" +…
- What is printed? java class LowBalanceException extends Exception { LowBalanceException(String m) { super(m); } } class Account { double…
- What is printed? java public class Main { public static void main(String[] args) throws Exception { try { method1(); } catch…
- What is printed? java public class Main { static class Resource implements AutoCloseable { public void close() { System.out.print("closed…
- What happens when this is compiled? java class Base { void risky() throws java.io.IOException {} } class Sub extends Base { @Override void…