Java ProgramsCollectionsStack Using Deque

Stack Using Deque in Java

intermediate·  Collections  ·  Queue & Stack

Problem

Deque already defines push(), pop(), and peek() with exact stack semantics, so ArrayDeque can act as a stack directly — no separate Stack class is needed.

Push a few elements onto an ArrayDeque used as a stack, then pop and peek to confirm last-in-first-out order.

Input
push("first"), push("second"), push("third")
Output
Top: third Pop: third Pop: second Remaining top: first

Java Program

Java
import java.util.ArrayDeque; import java.util.Deque; public class StackUsingDeque { public static void main(String[] args) { Deque<String> stack = new ArrayDeque<>(); stack.push("first"); stack.push("second"); stack.push("third"); // most recently pushed — now on top System.out.println("Top: " + stack.peek()); System.out.println("Pop: " + stack.pop()); System.out.println("Pop: " + stack.pop()); System.out.println("Remaining top: " + stack.peek()); } }

Output

Top: third Pop: third Pop: second Remaining top: first

Core Logic

Declaring the variable as a Deque and backing it with ArrayDeque gets the exact same push/pop/peek stack behavior the legacy Stack class offers, without any of Stack's baggage.

How It Works
  1. 1Deque<String> stack = new ArrayDeque<>(); declares the variable by its interface, backed by ArrayDeque.
  2. 2push("first"), push("second"), push("third") each add to the same end, so the most recently pushed element is always on top.
  3. 3peek() reads the top element without removing it — "third", the last one pushed.
  4. 4pop() removes and returns the top element each time — first "third", then "second" — leaving "first" as the new top.
After pushing first, second, third, the two pop() calls return third and second in that order, leaving first as the only remaining element.
💡

Key Point: The JDK's own documentation recommends ArrayDeque over java.util.Stack for stack usage today — Stack is a legacy class that extends the little-used Vector and carries synchronization overhead nothing here actually needs, while ArrayDeque is unsynchronized and generally faster.

Complexity
Time Complexity: O(1)Space Complexity: O(n)

Why: push(), pop(), and peek() each work on one end of the backing resizable array in amortized constant time, while the stack holds up to n elements at once.

Key Concepts

ArrayDequepush()pop()stack semantics

Related Programs