ProgrammingHardProduct-company placement · Java

What is printed?

What is printed?
Stack<Integer> st = new Stack<>();
Deque<Integer> dq = new ArrayDeque<>();
for (int i = 1; i <= 3; i++) { st.push(i); dq.push(i); }
System.out.print(st + " " + dq);
  1. A. [3, 2, 1] [3, 2, 1]
  2. B. [1, 2, 3] [3, 2, 1]
  3. C. [1, 2, 3] [1, 2, 3]
  4. D. [3, 2, 1] [1, 2, 3]

Correct answer: B. [1, 2, 3] [3, 2, 1]

Stack extends Vector and push appends at the END, so it prints bottom to top. ArrayDeque.push inserts at the HEAD and a deque prints head first, so the top comes first.

More OOP with C++ and Java questions

Exams that ask this topic