LearnFrenzy
Sign in Take a free test

Data Structures in Java · Data Structures in Java Output Questions · Question 3

Adding and removing at both ends of a deque Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    public static void main(String[] args) {
        Deque<Integer> dq = new ArrayDeque<>();
        dq.offerFirst(1);
        dq.offerLast(2);
        dq.offerFirst(3);
        dq.offerLast(4);
        System.out.println(dq + " " + dq.pollLast() + " " + dq.pollFirst() + " " + dq);
    }
}
  • A [1, 2, 3, 4] 4 1 [2, 3]
  • B [3, 1, 2, 4] 3 4 [1, 2]
  • C [3, 1, 2, 4] 4 3 [1, 2] Correct
  • D [4, 2, 1, 3] 3 4 [2, 1]
Correct Answer: Option C

The operands of + are evaluated left to right, so the first toString runs before either poll.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links