Skip to lesson

Stacks: last in, first out

A stack is a linear data structure that follows the Last-In First-Out principle. The last element added to the stack is the first element removed.

The LIFO principle: push, pop and peek

A stack is a collection where the last element added is the first one removed (LIFO), using push to add and pop to remove from the top.

A stack enforces Last-In, First-Out (LIFO) ordering where only the most recently added element is accessible. A stack maintains a dedicated top pointer, delivering push, pop, and peek in constant O(1) time.

Java
int[] data = new int[10];int top = -1;                   // -1 means the stack is emptydata[++top] = 10;               // push 10data[++top] = 20;               // push 20int peeked = data[top];         // peek: 20, still on the stackint popped = data[top--];       // pop: 20 (last in, first out)

Why not use an unsorted list without a top pointer? Searching an unsorted list for the latest item requires scanning all elements in O(n) time. Removing items from the front of an array requires shifting every remaining item in O(n) time. Trace push and pop operations on an empty stack: Start with empty stack []. push(10): stack becomes [10]. push(20): stack becomes [10, 20]. push(30): stack becomes [10, 20, 30]. pop(): removes top item 30; stack becomes [10, 20]. peek(): inspects top item 20 without removing it. pop(): removes 20; next pop() removes 10, leaving the stack empty.

Edge cases include stack underflow when attempting to pop or peek an empty stack. Fixed-capacity array stacks can also trigger stack overflow when pushing to a full array. Calling isEmpty() before pop prevents unexpected EmptyStackException errors.

  • push(e): adds an element to the top in O(1) time.
  • pop(): removes and returns the top element in O(1) time.
  • peek(): reads the top element without removing it in O(1) time.
  • isEmpty(): checks whether the stack contains any items.
  1. Call push(10) to place 10 on the empty stack.
  2. Call push(20) to place 20 above 10.
  3. Call peek() to inspect 20 while keeping it on the stack.
  4. Call pop() to remove and return 20.

Predict the output

Which item comes out?

Read the code and pick what it prints.

Round 1 of 3

Deque<Integer> s = new ArrayDeque<>();
s.push(1);
s.push(2);
s.push(3);
s.pop();
System.out.println(s.peek());

Why modern Java uses ArrayDeque instead of Stack

Java includes an older class named java.util.Stack. That legacy class extends Vector from Java 1.0.

Because Stack extends Vector, every method is synchronized. This synchronization adds thread locking overhead even in single-threaded code. Vector also allows index operations like get(0), violating the stack contract.

Example 1 · Basic Stack Operations Using ArrayDeque

BasicStackOperationsDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class BasicStackOperationsDemo {    public static void main(String[] args) {        Deque<Integer> stack = new ArrayDeque<>();        stack.push(10);        stack.push(20);        stack.push(30);
        System.out.println("Top element: " + stack.peek());        System.out.println("Popped: " + stack.pop());        System.out.println("New top: " + stack.peek());        System.out.println("Is empty: " + stack.isEmpty());    }}
Output
Top element: 30
Popped: 30
New top: 20
Is empty: false

What this code does

  • stack.push(30) places 30 on top of the stack.
  • stack.pop() removes 30 and reveals 20 as the new top element.
  • All stack operations run in O(1) time.

Modern Java uses Deque<T> stack = new ArrayDeque<>(). It is unsynchronized, faster, and backed by a dynamic array buffer.

Legacy Stack versus ArrayDeque:

  • Legacy Stack: synchronizes every call, hurting performance.
  • Legacy Stack: allows index access like get(2), breaking LIFO rules.
  • Modern ArrayDeque: cache-friendly array buffer with no lock overhead.
Never use java.util.Stack in modern Java code. Always declare Deque<T> stack = new ArrayDeque<>().

Real-world uses: undo history and the call stack

Text editors store user actions on an undo stack. Typing a word pushes that action. Pressing undo pops the latest action and reverts it.

Example 2 · Simulating Text Editor Undo with a Stack

TextEditorUndoDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class TextEditorUndoDemo {    public static void main(String[] args) {        Deque<String> history = new ArrayDeque<>();        history.push("Type hello");        history.push("Type world");        history.push("Make bold");
        System.out.println("Current action: " + history.peek());        System.out.println("Undo: " + history.pop());        System.out.println("Undo: " + history.pop());        System.out.println("Remaining on stack: " + history.peek());    }}
Output
Current action: Make bold
Undo: Make bold
Undo: Type world
Remaining on stack: Type hello

What this code does

  • Each edit action is pushed onto the history stack.
  • The undo operation pops the most recent action first.
  • Type hello remains on the stack as the earliest action.

Example 3 · Reversing a Word Using a Stack

ReverseWordStackDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;
public class ReverseWordStackDemo {    public static void main(String[] args) {        String word = "mentor";        Deque<Character> stack = new ArrayDeque<>();        for (char ch : word.toCharArray()) {            stack.push(ch);        }
        StringBuilder reversed = new StringBuilder();        while (!stack.isEmpty()) {            reversed.append(stack.pop());        }        System.out.println("Original: " + word);        System.out.println("Reversed: " + reversed);    }}
Output
Original: mentor
Reversed: rotnem

What this code does

  • Characters are pushed from left to right.
  • Popping elements reverses their order because the last character pops first.
  • Reversal completes in O(n) time and O(n) space.

The Java Virtual Machine uses a call stack to execute methods. When method main calls helper, the JVM pushes a stack frame for helper. When helper returns, its frame pops. Syntax parsers and web browser back buttons also rely on stacks.

Where stacks appear:

  • Text editor undo: reverts the most recent edit first.
  • JVM call stack: tracks nested method execution frames.
  • Browser history: pops visited pages in reverse order.

Next step

Check your understanding

10 quick questions