ProgrammingHardAmazon/Microsoft SDE MCQ · Java placement
Which lines fail to compile?
Which lines fail to compile?
List<Integer> ints = new ArrayList<>(); List<Number> a = ints; // line 1 List<? extends Number> b = ints; // line 2 b.add(Integer.valueOf(3)); // line 3 Number n = b.isEmpty() ? null : b.get(0); // line 4 List<? super Integer> c = new ArrayList<Number>(); c.add(4); // line 5
- A. Lines 1 and 3 only
- B. Lines 1, 3 and 5
- C. Line 3 only
- D. Lines 1 and 5 only
Correct answer: A. Lines 1 and 3 only
Generics are invariant, so List<Integer> is not a List<Number> (line 1). A List<? extends Number> can be read as Number but nothing except null can be added (line 3). ? super Integer accepts Integer additions (line 5 is fine).
More OOP with C++ and Java questions
- What happens? java boolean flag = true; Integer none = null; Integer r1 = flag ? null : 0; System.out.print(r1); Integer r2 = flag ? none…
- What is printed? java System.out.print(Math.abs(Integer.MINVALUE) + " "); System.out.print(Integer.MAXVALUE + 1 == Integer.MINVALUE);
- What is printed? java System.out.print((-7 / 2 == -3) + " " + (-7 % 2 == 1) + " " + (Math.floorMod(-7, 2) == 1) + " " + (7 % -2 == 1));
- Which line fails to compile? java byte b = 10; b += 5; // line 1 b++; // line 2 b = b + 1; // line 3 b = 10 + 20; // line 4
- What is printed? java int i = 0, j = 0; boolean p = (i++ > 0) & (i++ > 0); boolean q = (j++ > 0) && (j++ > 0); System.out.print(i + " " +…
- What is printed? java class P { private void f() { System.out.print("P"); } void call() { f(); } } class C extends P { void f() {…