ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
List<Integer> l = new ArrayList<>(List.of(2, 2, 3, 2, 4));
for (int i = 0; i < l.size(); i++)
if (l.get(i) == 2) l.remove(i);
System.out.print(l);- A. [3, 4]
- B. [2, 3, 4]
- C. [2, 3, 2, 4]
- D. A ConcurrentModificationException is thrown
Correct answer: B. [2, 3, 4]
Removing at index i shifts the next element into index i, but the loop then moves on to i + 1 and skips it: the second 2 survives. An index loop does not throw ConcurrentModificationException.
More OOP with C++ and Java questions
- What is printed? java Set<String> s = new HashSet<>(); System.out.print(s.add("a") + " " + s.add("a") + " " + s.remove("b") + " " +…
- What is printed? java Map<String, Integer> m = Map.of("a", 1, "a", 2); System.out.print(m);
- What is printed? java interface A { default String hi() { return "A"; } } interface B extends A { default String hi() { return "B"; } }…
- What is printed? java // static methods of the main class: static void f(Object o) { System.out.print("O"); } static void f(Number n) {…
- A base type must hold common fields, have a constructor that validates them, and share some method bodies, while subclasses form a strict…
- java.io.BufferedReader wraps another Reader, is itself a Reader, and adds buffering on top of it; such wrappers can be stacked at run…