ProgrammingHardAmazon/Microsoft SDE MCQ · Java placement
What is printed?
What is printed?
List<Integer> l = new ArrayList<>(List.of(5, 6, 7)); Iterator<Integer> it = l.iterator(); while (it.hasNext()) if (it.next() % 2 == 1) it.remove(); l.add(0, 1); l.remove(Integer.valueOf(6)); System.out.print(l + " " + l.size());
- A. [1] 1
- B. [1, 6] 2
- C. [6] 1
- D. [1, 7] 2
Correct answer: A. [1] 1
Iterator.remove is the safe way to delete while iterating, leaving [6]. add(0, 1) gives [1, 6], and remove(Integer.valueOf(6)) removes the value 6 (not index 6), leaving [1] with size 1.
More OOP with C++ and Java questions
- What does this Java program print? class A { String n = "A"; String get() { return n; } } class B extends A { String n = "B"; String get()…
- What does this Java program print? class P { P() { init(); } void init() { System.out.print("P "); } } class C extends P { int x = 5; C()…
- What does this Java code print? Integer a = 127, b = 127, c = 128, d = 128; System.out.println((a == b) + " " + (c == d) + " " +…
- What does this Java code print? class A { String n = "A"; String get() { return n; } } class B extends A { String n = "B"; String get() {…
- What does this Java program print? class P { static { System.out.print("1"); } { System.out.print("2"); } P() { System.out.print("3"); } }…
- What does this Java program print? static int f() { int x = 1; try { return x; } finally { x = 3; } } static int g() { try { throw new…