Skip to lesson
MentorNxt home

Java Programming

Queues, Stacks & Priority Queues

Stacks with ArrayDeque

A stack is a collection where the last value added is the first one taken out: last in, first out, or LIFO. In Java you build one with ArrayDeque and its push, pop and peek methods.

Last in, first out

A stack is a collection where values are added and removed at the same end, called the top, so the last value added is the first one removed. This rule is called last in, first out (LIFO).

A stack follows one rule: last in, first out. Think of a pile of parcels on the packing desk of an online store. A packed parcel goes on top, and the courier takes the parcel from the top. The parcel put down last is picked up first. The end you work with is called the top.

This order is exactly what many programs need. The Undo button cancels your most recent change first. The phone's Back button returns to the screen you saw most recently. When you read brackets like {[(, the bracket opened last must be closed first.

Java itself uses a stack for method calls: each call is placed on top, and it is removed when the method returns. Endless recursion fills this stack, which is the StackOverflowError you may have seen.

A stack of three orders: Order 3 on top, Order 2 below it and Order 1 at the bottom. push(x) puts a new order on the top and pop() takes the top order off. The last order in is the first one out.

A stack with ArrayDeque

push puts a value on top of a stack, and pop removes and returns the top value. peek looks at the top value without removing it. pop on an empty stack throws NoSuchElementException.

Declare it with the Deque interface: Deque<String> stack = new ArrayDeque<>();. A deque (say "deck") can add and remove at both ends; a stack simply uses one end, the front, as its top.

Example 1 · push, pop and peek

StackBasicsDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class StackBasicsDemo {    public static void main(String[] args) {        Deque<String> parcels = new ArrayDeque<>();        parcels.push("Parcel 1");        parcels.push("Parcel 2");        parcels.push("Parcel 3");        System.out.println("Pile (top first): " + parcels);        System.out.println("On top: " + parcels.peek());
        System.out.println("Taken: " + parcels.pop());        System.out.println("Taken: " + parcels.pop());        parcels.push("Parcel 4");        System.out.println("Pile now: " + parcels + ", size " + parcels.size());    }}
Output
Pile (top first): [Parcel 3, Parcel 2, Parcel 1]
On top: Parcel 3
Taken: Parcel 3
Taken: Parcel 2
Pile now: [Parcel 4, Parcel 1], size 2

What this code does

  • Parcel 3 was pushed last, so it is on top: peek shows it and the first pop takes it.
  • Compare with a queue: the same three values in a queue would come out as Parcel 1 first.

Example 2 · Undo history in a notes app

UndoDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class UndoDemo {    static String text = "";    static Deque<String> history = new ArrayDeque<>();
    static void type(String words) {        history.push(text);        text = text + words;        System.out.println("Typed    -> \"" + text + "\"");    }
    static void undo() {        if (history.isEmpty()) {            System.out.println("Nothing to undo");            return;        }        text = history.pop();        System.out.println("Undo     -> \"" + text + "\"");    }
    public static void main(String[] args) {        type("Buy pens");        type(", files");        type(", stapler");        undo();        undo();        type(", tape");        undo();        undo();        undo();    }}
Output
Typed    -> "Buy pens"
Typed    -> "Buy pens, files"
Typed    -> "Buy pens, files, stapler"
Undo     -> "Buy pens, files"
Undo     -> "Buy pens"
Typed    -> "Buy pens, tape"
Undo     -> "Buy pens"
Undo     -> ""
Nothing to undo

What this code does

  • Before every change, the old text is pushed. Undo pops the most recent old text and puts it back, so changes are undone newest first.
  • The isEmpty() check turns an extra Undo press into a friendly message instead of a NoSuchElementException.

Example 3 · Mistake: pop on an empty stack

EmptyPopDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class EmptyPopDemo {    public static void main(String[] args) {        Deque<String> screens = new ArrayDeque<>();        screens.push("Home");        screens.push("Cart");        System.out.println("Back to: " + screens.pop());        System.out.println("Back to: " + screens.pop());        System.out.println("Back to: " + screens.pop());    }}
Sample output
Back to: Cart
Back to: Home
Exception in thread "main" java.util.NoSuchElementException
	at java.base/java.util.ArrayDeque.removeFirst(ArrayDeque.java:362)
	at java.base/java.util.ArrayDeque.pop(ArrayDeque.java:593)
	at EmptyPopDemo.main(EmptyPopDemo.java:11)

What this code does

  • The third pop() finds an empty stack. On a deque, pop is the same as removeFirst, which is why the trace names it.
  • Fix: check screens.isEmpty() first, or use poll(), which returns null on an empty deque instead of throwing.
  • push(x): put x on top.
  • pop(): remove and return the top value; throws NoSuchElementException if the stack is empty.
  • peek(): return the top value without removing it; returns null if empty.
  • isEmpty() and size() as usual. Printing or for-each shows the top first. All of these are O(1).

Order of execution

Which order do the values come out?

Put the printed lines in the order the program prints them.

Deque<String> stack = new ArrayDeque<>();
stack.push("Order 1");
stack.push("Order 2");
stack.push("Order 3");
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
Check isEmpty() before pop() whenever an empty stack is possible, for example when the user presses Undo with nothing to undo.

Why not the Stack class?

Java also has an old class called Stack, from Java 1.0. Its own documentation recommends Deque instead. The example below shows the surprise it causes.

Example 4 · Why the old Stack class is risky

OldStackDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;import java.util.Stack;
public class OldStackDemo {    public static void main(String[] args) {        Stack<String> old = new Stack<>();        Deque<String> modern = new ArrayDeque<>();        for (String s : new String[] { "a", "b", "c" }) {            old.push(s);            modern.push(s);        }        System.out.println("Stack prints:      " + old);        System.out.println("ArrayDeque prints: " + modern);        System.out.println("Both pop: " + old.pop() + " and " + modern.pop());
        old.add(0, "sneaky");        old.remove(1);        System.out.println("Stack after list tricks: " + old);    }}
Output
Stack prints:      [a, b, c]
ArrayDeque prints: [c, b, a]
Both pop: c and c
Stack after list tricks: [sneaky, b]

What this code does

  • Both pop c, so the LIFO behaviour is the same, but Stack prints from the bottom and ArrayDeque from the top.
  • Stack inherits list methods, so code can insert at the bottom and delete from the middle. A Deque used with push/pop/peek keeps the stack honest.

First, Stack extends Vector, so it also has list methods like get(0), add(0, x) and remove(2). Any code can reach into the middle and break the last-in-first-out rule. Second, every method takes a lock meant for programs that run several tasks at once, which costs time in normal programs. Third, it prints and loops from the bottom up, the opposite of ArrayDeque, which confuses readers.

You will still meet Stack in old code and in some textbooks. Read it, but write new code with ArrayDeque.

The balanced-brackets idea

Checking brackets like {[()]} is the classic stack problem. Every closing bracket must match the most recent unclosed opening bracket, and "most recent" is what a stack's top gives you.

  1. Read the text one character at a time.
  2. Opening bracket (, [ or {: push it.
  3. Closing bracket: if the stack is empty, it is unbalanced. Otherwise pop and check that the pair matches.
  4. Other characters: ignore them.
  5. At the end, the text is balanced only if the stack is empty.

Example 5 · Balanced brackets checker

BracketsDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class BracketsDemo {    static boolean isBalanced(String text) {        Deque<Character> open = new ArrayDeque<>();        for (char c : text.toCharArray()) {            if (c == '(' || c == '[' || c == '{') {                open.push(c);            } else if (c == ')' || c == ']' || c == '}') {                if (open.isEmpty()) {                    return false;                }                char top = open.pop();                boolean pair = (top == '(' && c == ')')                        || (top == '[' && c == ']')                        || (top == '{' && c == '}');                if (!pair) {                    return false;                }            }        }        return open.isEmpty();    }
    public static void main(String[] args) {        String[] tests = { "{[()]}", "if (a[i] > 0) { x++; }", "([)]", "((", "a(b)c]" };        for (String t : tests) {            System.out.println(t + "  ->  " + (isBalanced(t) ? "balanced" : "NOT balanced"));        }    }}
Output
{[()]}  ->  balanced
if (a[i] > 0) { x++; }  ->  balanced
([)]  ->  NOT balanced
((  ->  NOT balanced
a(b)c]  ->  NOT balanced

What this code does

  • In ([)], the ) arrives while [ is on top, so the pair check fails. In ((, nothing goes wrong during the loop, but two brackets are still open at the end.
  • In a(b)c], the ] comes when the stack is already empty: a closing bracket with no opener. Characters that are not brackets are skipped.

Next step

Check your understanding

12 quick questions