ProgrammingHardProduct-company placement · Java
Which lines fail to compile?
Which lines fail to compile?
List<Integer> ints = new ArrayList<>(); List<Number> nums = ints; // L1 List<? extends Number> ext = ints; // L2 ext.add(5); // L3 Number n = ext.isEmpty() ? null : ext.get(0); // L4
- A. L1 and L3
- B. L1 only
- C. L3 only
- D. L1, L3 and L4
Correct answer: A. L1 and L3
Generics are invariant: List<Integer> is not a List<Number> (L1). With ? extends Number the compiler does not know the element type, so nothing but null can be added (L3), while reading as Number is fine.
More OOP with C++ and Java questions
- Which lines fail to compile? java List<? super Integer> l = new ArrayList<Number>(); l.add(1); // L1 l.add(2.5); // L2 Object o =…
- What is printed? java Object[] arr = new String[2]; arr[0] = "ok"; try { arr[1] = 42; System.out.print("stored"); } catch…
- What is printed? java int[] a = {1, 2}, b = {1, 2}; int[][] p = {{1}}, q = {{1}}; System.out.print(a.equals(b) + " " + Arrays.equals(a, b)…
- What is printed? java String s = null; s += "x"; String t = "a" + null + 1 + 2; System.out.print(s + " " + t);
- What is printed? java StringBuilder sb = new StringBuilder("abcdef"); sb.insert(2, "XY").delete(5, 7).reverse().setCharAt(0, 'Z')…
- What is printed? java String s = "level"; String t = s.replace('l', 'p'); System.out.print(t + " " + (s.replace('z', 'q') == s) + " " + s);