Course contentsShow
← Java
Lesson 1212 of 2,87027. Queue and Deque ImplementationsFree lesson

push and pop: Stack Operations on Deque

Master the push and pop methods for adding and removing elements from the top of the stack using Deque.

push and pop: Stack Operations on Deque

You'll learn how to use push and pop methods to treat a Deque as a stack, adding and removing elements from the top.

The Core Idea

While Deque is a double-ended queue, it provides convenient stack methods that operate on one end consistently. The push method adds an element to the "top" of the stack (the front of the deque), and pop removes and returns the element from the top. These methods give you classic stack behavior—Last In, First Out (LIFO)—using a Deque implementation.

Think of it like a stack of plates: push places a new plate on top, and pop takes the top plate off.

The Methods

push(E element) – Adds an element to the front of the deque (the "top" of the stack). If the deque is capacity-restricted and full, it throws an IllegalStateException. Equivalent to addFirst.

pop() – Removes and returns the element at the front of the deque (the "top" of the stack). If the deque is empty, it throws a NoSuchElementException. Equivalent to removeFirst.

Example: Using ArrayDeque as a Stack

Deque<String> stack = new ArrayDeque<>();

// Push elements onto the stack
stack.push("First");
stack.push("Second");
stack.push("Third");

// Pop elements from the stack (LIFO order)
System.out.println(stack.pop());  // "Third"
System.out.println(stack.pop());  // "Second"
System.out.println(stack.pop());  // "First"
// stack is now empty

Notice that pop retrieves elements in the reverse order they were pushed—this is the defining characteristic of a stack.

Key Takeaway: push and pop provide intuitive stack semantics on Deque, always operating on the front/top of the collection with exception-throwing behavior when operations fail.