ProgrammingModerateHCL · Tech Mahindra pattern
What is printed?
What is printed?
List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(1, 5); System.out.print(list);
- A. [1, 5, 2]
- B. [1, 2, 1, 5]
- C. [1, 2, 5]
- D. [5, 2]
Correct answer: A. [1, 5, 2]
add(index, element) inserts 5 at index 1 and shifts the later elements right, so [1, 2] becomes [1, 5, 2]. It neither replaces (that is set) nor appends.
More OOP with C++ and Java questions
- What is printed? java Set<String> s = new HashSet<>(); s.add("a"); s.add("b"); s.add("a"); System.out.print(s.size() + " " + s.add("b"));
- What is printed? java try { System.out.print("T"); throw new RuntimeException(); } catch (Exception e) { System.out.print("C"); } finally…
- Why must a C++ copy constructor take its parameter by reference (A(const A &other)) rather than by value?
- What is printed? java System.out.print("placement".substring(2, 5) + "placement".indexOf('e'));
- What is the time complexity of get(i) on a Java ArrayList and on a LinkedList?
- In C++, what does new do that malloc does not?