Mastering Stack and Queue in Java

Mastering Stack and Queue in Java: Concepts, Implementations, and Best Practices

Reading Time: 15 min readAuthor: DeepTechHub
Mastering Stack and Queue in Java

Audio controls for Mastering Stack and Queue in Java

Listen to this article

Stacks and queues shape how Java programs process data: stacks handle the newest item first, while queues usually handle the oldest item first. These patterns appear in everyday workflows and common algorithms, and Java offers several collection implementations for each. This guide compares those choices and demonstrates them in practical examples.


The Big Picture: Understanding the Hierarchy

Before we dive into individual classes, let's map out where everything lives in the Java Collections Framework:

java.util.Collection (interface)
└── java.util.Queue (interface; ordering depends on implementation)
    ├── java.util.Deque (interface; supports both ends)
    │   ├── ArrayDeque (class)
    │   └── LinkedList (class; also implements List)
    └── PriorityQueue (class; priority ordering)
Queue branches into the double-ended Deque interface and the priority-based PriorityQueue; ArrayDeque and LinkedList implement Deque.

Queue is an interface, and its implementations define their ordering. Many queues are FIFO, while a PriorityQueue returns elements by priority. In java.util.concurrent, BlockingQueue extends Queue, and BlockingDeque extends both BlockingQueue and Deque. Examples include ArrayBlockingQueue, LinkedBlockingQueue, PriorityBlockingQueue, and LinkedBlockingDeque. ConcurrentLinkedQueue and ConcurrentLinkedDeque are thread-safe, non-blocking implementations; they do not implement the blocking interfaces.


Queue Fundamentals

What is a Queue?

A basic FIFO queue follows the First In, First Out principle: the first element added is the first removed. Think of a line at a coffee shop. Other queue implementations, such as PriorityQueue, use a different ordering.

enqueue(1) → [1]
enqueue(2) → [1, 2]
enqueue(3) → [1, 2, 3]
dequeue()  → returns 1, queue is [2, 3]

The Queue Interface: Two Sets of Methods

The Queue interface provides six core methods, organized into two families that handle errors differently:

OperationThrows ExceptionReturns null/false
Insert elementadd(e)offer(e)
Remove frontremove()poll()
Inspect frontelement()peek()

For a capacity-restricted queue, offer() lets you handle a full queue through its return value instead of an exception. poll() and peek() return null when the queue is empty. These methods can still throw for other invalid inputs, such as a null element where the implementation prohibits it.

Basic Queue Example

java
Queue<String> queue = new ArrayDeque<>();
 
// Enqueue
queue.offer("Customer 1");
queue.offer("Customer 2");
queue.offer("Customer 3");
 
// Peek (non-destructive)
System.out.println(queue.peek()); // Customer 1
 
// Dequeue
System.out.println(queue.poll()); // Customer 1
System.out.println(queue.poll()); // Customer 2

Stack Fundamentals

What is a Stack?

A stack follows LIFO (Last In, First Out). Think of a stack of plates: you add to the top and remove from the top.

push(1) → [1]
push(2) → [1, 2]
push(3) → [1, 2, 3]
pop()   → returns 3, stack is [1, 2]

Core Stack Methods

The Deque interface (which provides stack functionality) includes:

OperationMethodBehaviour
Pushpush(e)Add to top (front)
Poppop()Remove & return top, throws if empty
Peekpeek()View top without removing, returns null if empty
Check EmptyisEmpty()Boolean check
Sizesize()Number of elements

Basic Stack Example

java
Deque<Integer> stack = new ArrayDeque<>();
 
// Push
stack.push(10);
stack.push(20);
stack.push(30);
 
// Peek
System.out.println(stack.peek()); // 30
 
// Pop
System.out.println(stack.pop()); // 30
System.out.println(stack.pop()); // 20
 
// Check if empty
if (!stack.isEmpty()) {
    System.out.println(stack.peek()); // 10
}

Choosing Core Implementations

1. ArrayDeque: a good default

ArrayDeque is a good default for ordinary single-threaded stack and queue use. It implements Deque, so it supports operations at both ends. Its common end operations run in amortized constant time, though resizing can make an individual insertion take longer. It is not thread-safe. As with other generic collections, Deque<Integer> stores Integer references, so primitive values are boxed.

Why it is useful:

  • Uses a resizable array internally.

  • Supports stack, queue, and double-ended queue operations.

  • The JDK documentation notes it is likely faster than Stack for stack use and LinkedList for queue use.

Example: Using as Both Stack and Queue

java
Deque<Integer> dq = new ArrayDeque<>();
 
// Using as QUEUE (FIFO)
dq.offerLast(1);   // enqueue at back
dq.offerLast(2);
dq.offerLast(3);
System.out.println(dq.pollFirst()); // 1 (dequeue from front)
 
// Using as STACK (LIFO)
dq.push(10);       // push to front (top)
dq.push(20);
System.out.println(dq.pop());  // 20 (pop from front)
 
// Get explicit about your intent
dq.addFirst(100);  // same as push()
dq.removeFirst();  // same as pop()
dq.addLast(200);   // enqueue
dq.removeLast();   // remove from back

2. PriorityQueue: ordered by priority

Unlike a FIFO queue, PriorityQueue returns the least element according to its ordering at the head. By default it uses natural ordering, so integers come out smallest first. A custom comparator can change that order. Repeated poll() calls retrieve elements in priority order, but iterating over the queue does not guarantee sorted order.

Key characteristics:

  • Default: the least element is at the head (a min-heap for naturally ordered numbers).

  • Custom comparators supported

  • offer() and poll() take O(log n); peek() takes O(1).

  • NOT suitable for stack behaviour

Example: Min-Heap Priority Queue

java
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(30);
pq.offer(10);
pq.offer(20);
 
System.out.println(pq.poll()); // 10 (smallest)
System.out.println(pq.poll()); // 20
System.out.println(pq.poll()); // 30

Example: Max-Heap with Custom Comparator

java
PriorityQueue<Integer> maxHeap =
    new PriorityQueue<>((a, b) -> Integer.compare(b, a));
 
maxHeap.offer(30);
maxHeap.offer(10);
maxHeap.offer(20);
 
System.out.println(maxHeap.poll()); // 30 (largest)
System.out.println(maxHeap.poll()); // 20
System.out.println(maxHeap.poll()); // 10

Example: Objects with Priority

Here, a lower numeric value means a higher priority, so priority 1 is processed before priority 3.

java
class Task implements Comparable<Task> {
    String name;
    int priority;
 
    public Task(String name, int priority) {
        this.name = name;
        this.priority = priority;
    }
 
    @Override
    public int compareTo(Task other) {
        return Integer.compare(this.priority, other.priority);
    }
}
 
PriorityQueue<Task> taskQueue = new PriorityQueue<>();
taskQueue.offer(new Task("Email", 3));
taskQueue.offer(new Task("Report", 1));
taskQueue.offer(new Task("Meeting", 2));
 
// Process the highest-priority task first (smallest number in this example)
while (!taskQueue.isEmpty()) {
    Task t = taskQueue.poll();
    System.out.println("Processing: " + t.name + " (priority: " + t.priority + ")");
}
// Output:
// Processing: Report (priority: 1)
// Processing: Meeting (priority: 2)
// Processing: Email (priority: 3)

3. LinkedList: a list and a deque

LinkedList implements both List and Deque, so one object can be used through either interface. Indexed access is available, but it walks through the list.

When to use:

  • Need both queue/stack AND list operations

  • Comfortable with slower performance than ArrayDeque

Example:

java
LinkedList<String> linked = new LinkedList<>();
Deque<String> asDeque = linked;
asDeque.push("First");
asDeque.push("Second");
 
// The same object can also be referenced through List
List<String> list = linked;
System.out.println(list.get(0)); // Second

Use LinkedList when you need both interfaces, not for frequent get(index) calls. Its linked nodes generally use more memory than an array-backed deque.

4. BlockingQueue: coordinate producers and consumers

BlockingQueue is an interface in java.util.concurrent. Its put() and take() operations wait when the queue is full or empty, which can coordinate producer and consumer threads. Blocking behavior and thread safety do not imply one universal performance complexity; that depends on the concrete implementation.

Key methods:

  • put(e) — Insert, blocks if queue is full

  • take() — Remove from front, blocks if queue is empty

  • offer(e, timeout, unit) — Insert with timeout

  • poll(timeout, unit) — Remove with timeout

Example: Producer-consumer with a stop value

The producer adds a sentinel value after its work. The consumer exits when it receives that value. This illustrates normal shutdown; production code also needs a policy for worker failure and cancellation.

Assume the statements below are in a method that can throw InterruptedException for the two join() calls.

java
BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(2);
 
final int STOP = -1; // Not used as a regular item
 
// Producer thread
Thread producer = new Thread(() -> {
    try {
        for (int i = 1; i <= 5; i++) {
            System.out.println("Producing: " + i);
            queue.put(i);
        }
        queue.put(STOP);
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
});
 
// Consumer thread
Thread consumer = new Thread(() -> {
    try {
        while (true) {
            Integer value = queue.take();
            if (value == STOP) {
                break;
            }
            System.out.println("Consuming: " + value);
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    }
});
 
consumer.start();
producer.start();
producer.join();
consumer.join();

5. Concurrent collections

Use these when multiple threads access a collection without waiting for capacity or data. They are thread-safe, but their behavior and performance differ by implementation; they are not all interchangeable.

java
// Thread-safe non-blocking deque used as a stack
Deque<Integer> safeStack = new ConcurrentLinkedDeque<>();
safeStack.push(1);
safeStack.pop();
 
// Thread-safe non-blocking FIFO queue
Queue<Integer> safeQueue = new ConcurrentLinkedQueue<>();
safeQueue.offer(1);
safeQueue.poll();
 
// Blocking deque for producer-consumer coordination at both ends
BlockingDeque<Integer> blockingDeque = new LinkedBlockingDeque<>(10);
blockingDeque.putFirst(1);
blockingDeque.takeFirst();

When to Use What

Use this table as a starting point; choose based on ordering, capacity, and whether operations should block:

ScenarioBest ChoiceWhy
Simple FIFO queueArrayDequeSimple, amortized constant-time end operations; single-threaded
Simple LIFO stackArrayDequeSimple, amortized constant-time end operations; single-threaded
Need element priorityPriorityQueueOrdered by comparison
Need both List + DequeLinkedListSupports both interfaces
Single-threaded BFSArrayDequePerfect for graph traversal
Single-threaded DFSArrayDequePerfect for tree traversal
Producer-consumer patternBlockingQueueThread-safe, blocking
Multiple threads, non-blocking FIFOConcurrentLinkedQueueThread-safe operations without waiting for capacity or data
Multiple threads, priority orderPriorityBlockingQueueThread-safe priority queue; unbounded, with blocking retrieval when empty
Replace legacy stack codeArrayDequeUse Deque methods instead of Stack

Real-World Examples & Patterns

Pattern 1: Balanced Parentheses

A classic stack problem: check if brackets are balanced.

java
public boolean isBalanced(String s) {
    Deque<Character> stack = new ArrayDeque<>();
    Map<Character, Character> pairs = new HashMap<>();
    pairs.put(')', '(');
    pairs.put(']', '[');
    pairs.put('}', '{');
 
    for (char c : s.toCharArray()) {
        if (pairs.containsValue(c)) {
            // Opening bracket
            stack.push(c);
        } else if (pairs.containsKey(c)) {
            // Closing bracket
            if (stack.isEmpty() || !stack.pop().equals(pairs.get(c))) {
                return false;
            }
        }
    }
    return stack.isEmpty();
}
 
// Usage
System.out.println(isBalanced("({[]})")); // true
System.out.println(isBalanced("({[}])")); // false

Pattern 2: BFS (Breadth-First Search)

Queues are essential for BFS in graphs and trees.

java
class TreeNode {
    int val;
    TreeNode left, right;
    TreeNode(int val) { this.val = val; }
}
 
public List<Integer> levelOrderBFS(TreeNode root) {
    List<Integer> result = new ArrayList<>();
    if (root == null) return result;
 
    Queue<TreeNode> queue = new ArrayDeque<>();
    queue.offer(root);
 
    while (!queue.isEmpty()) {
        TreeNode node = queue.poll();
        result.add(node.val);
 
        if (node.left != null) queue.offer(node.left);
        if (node.right != null) queue.offer(node.right);
    }
    return result;
}

Pattern 3: DFS with Explicit Stack

Stacks replace recursion in iterative DFS.

java
public List<Integer> postOrderDFS(TreeNode root) {
    List<Integer> result = new ArrayList<>();
    if (root == null) return result;
 
    Deque<TreeNode> stack = new ArrayDeque<>();
    stack.push(root);
    TreeNode prev = null;
 
    while (!stack.isEmpty()) {
        TreeNode curr = stack.peek();
 
        // Going down the tree
        if (prev == null || prev.left == curr || prev.right == curr) {
            if (curr.left != null) {
                stack.push(curr.left);
            } else if (curr.right != null) {
                stack.push(curr.right);
            } else {
                result.add(curr.val);
                stack.pop();
            }
        }
        // Going up (left subtree done)
        else if (curr.left == prev) {
            if (curr.right != null) {
                stack.push(curr.right);
            } else {
                result.add(curr.val);
                stack.pop();
            }
        }
        // Going up (right subtree done)
        else if (curr.right == prev) {
            result.add(curr.val);
            stack.pop();
        }
 
        prev = curr;
    }
    return result;
}

Pattern 4: Monotonic Stack

A clever pattern for "Next Greater Element" problems.

java
public int[] nextGreaterElement(int[] nums) {
    int[] result = new int[nums.length];
    Deque<Integer> stack = new ArrayDeque<>();
 
    // Process from right to left
    for (int i = nums.length - 1; i >= 0; i--) {
        // Pop smaller or equal elements
        while (!stack.isEmpty() && stack.peek() <= nums[i]) {
            stack.pop();
        }
 
        // Top of stack is next greater (or -1 if empty)
        result[i] = stack.isEmpty() ? -1 : stack.peek();
 
        // Push current element
        stack.push(nums[i]);
    }
 
    return result;
}
 
// Usage
int[] nums = {1, 2, 1};
int[] result = nextGreaterElement(nums);
// result = {2, -1, -1}

Pattern 5: Undo/Redo Functionality

Stacks are perfect for undo/redo systems.

java
class TextEditor {
    private Deque<String> undoStack = new ArrayDeque<>();
    private Deque<String> redoStack = new ArrayDeque<>();
    private String currentText = "";
 
    public void type(String text) {
        undoStack.push(currentText);
        currentText += text;
        redoStack.clear(); // Clear redo when new action is performed
    }
 
    public void undo() {
        if (!undoStack.isEmpty()) {
            redoStack.push(currentText);
            currentText = undoStack.pop();
        }
    }
 
    public void redo() {
        if (!redoStack.isEmpty()) {
            undoStack.push(currentText);
            currentText = redoStack.pop();
        }
    }
 
    public String getText() {
        return currentText;
    }
}

Performance Considerations

The useful complexity comparisons are the common end operations. Actual performance also depends on collection size, workload, and JVM.

ImplementationCommon operationsNotes
ArrayDequeEnd insertions and removals are amortized O(1); inspect an end in O(1).Resizable array; not thread-safe.
LinkedListAdd or remove at either end in O(1); indexed access is O(n).Linked nodes; not thread-safe.
PriorityQueueoffer() and poll() are O(log n); peek() is O(1).Priority order, not FIFO; not thread-safe.
BlockingQueueVaries by implementation.An interface; blocking and thread safety describe behavior, not one complexity.

Array-backed collections store element references in an array. LinkedList stores elements in linked nodes, which usually has higher memory overhead. The exact cost depends on the JVM and its object layout. For ordinary single-threaded stack and queue tasks, ArrayDeque is a practical default; benchmark your own workload if performance is important.


Multithreading with Collections

External synchronization

Collections provides synchronized wrappers for some collection types, but no synchronizedQueue() or synchronizedDeque(). Such wrappers protect individual method calls; iteration and compound workflows still need an external lock. To share an ArrayDeque, protect every access with the same monitor:

java
Queue<Integer> sharedQueue = new ArrayDeque<>();
synchronized (sharedQueue) {
    sharedQueue.offer(1);
    if (!sharedQueue.isEmpty()) {
        sharedQueue.poll();
    }
    for (Integer value : sharedQueue) {
        System.out.println(value);
    }
}

Here, sharedQueue is an ArrayDeque referenced as a Queue. A deque uses the same approach. Holding the monitor around a check-and-remove sequence makes that compound operation atomic:

java
Deque<Integer> sharedDeque = new ArrayDeque<>();
synchronized (sharedDeque) {
    if (!sharedDeque.isEmpty()) {
        Integer value = sharedDeque.pop();
        System.out.println(value);
    }
}

sharedDeque is an ArrayDeque; every thread that accesses it must use that same monitor. Synchronizing only one operation at a time would not make a multi-step workflow atomic.

When to Use Each

  • External synchronization — Simple shared access; compound operations and iteration need the same monitor.

  • Concurrent collections — Thread-safe operations without waiting for data or capacity.

  • BlockingQueue/Deque — Producer-consumer workflows that coordinate through waiting and, for bounded queues, provide backpressure.


Common Pitfalls & Best Practices

❌ Pitfall 1: Using the Legacy Stack Class

java
// DON'T DO THIS
Stack<Integer> legacyStack = new Stack<>();
 
// DO THIS INSTEAD
Deque<Integer> stack = new ArrayDeque<>();

The Stack class is a legacy subclass of Vector with synchronized methods you don't need. ArrayDeque is faster and more idiomatic.

❌ Pitfall 2: Mixing Up Queue Behavior

java
// WRONG: PriorityQueue is NOT FIFO
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(30);
pq.offer(10);
pq.offer(20);
System.out.println(pq.poll()); // 10, not 30!
 
// RIGHT: Use ArrayDeque for FIFO
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(30);
queue.offer(10);
queue.offer(20);
System.out.println(queue.poll()); // 30 (FIFO)

❌ Pitfall 3: Not Checking Empty Before Pop

java
Deque<Integer> stack = new ArrayDeque<>();
// stack.pop(); // Throws NoSuchElementException if empty
 
if (!stack.isEmpty()) {
    Integer top = stack.pop();
}
 
// peek() returns null if empty
Integer nextTop = stack.peek();

✅ Best Practice 1: Be Explicit with Method Names

java
// Good: Intent is clear
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.pop();
 
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(1);
queue.poll();
 
// Also good: Using Deque methods explicitly
Deque<Integer> dq = new ArrayDeque<>();
dq.addFirst(1);   // Push
dq.removeFirst(); // Pop
dq.addLast(1);    // Enqueue
dq.removeFirst(); // Dequeue

Key takeaways

Here are the key takeaways to remember:

  1. Use ArrayDeque by default for ordinary single-threaded stacks and queues; its common end operations are amortized O(1).

  2. Never use the legacy Stack class—use Deque with ArrayDeque instead.

  3. Know your intent:

    • FIFO → ArrayDeque with queue methods

    • LIFO → ArrayDeque with stack methods

    • Priority → PriorityQueue

  4. PriorityQueue iteration is not sorted; use repeated poll() calls to retrieve elements by priority.

  5. LinkedList indexed access is O(n), and its linked nodes add memory overhead.

  6. For multiple threads, choose a concurrent collection for non-blocking access or a blocking queue when producers and consumers should wait for each other.

  7. Always check for empty before calling pop() or remove() unless you want an exception.

  8. Prefer safe methods: Use offer(), poll(), and peek() over add(), remove(), and element() for bounded or concurrent scenarios.

Did you find this article useful?