ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
List<Integer> l = new ArrayList<>(10); System.out.print(l.size() + " "); l.set(0, 1); System.out.print(l);
- A. 0 [1]
- B. 10 [1, null, null, …]
- C. "10 " is printed, then IndexOutOfBoundsException is thrown
- D. "0 " is printed, then IndexOutOfBoundsException is thrown
Correct answer: D. "0 " is printed, then IndexOutOfBoundsException is thrown
The constructor argument is the initial CAPACITY, not the size; the list is empty, and set(0, …) requires an existing element at index 0.
More OOP with C++ and Java questions
- What is printed? java 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)…
- 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…