Java Stack

Beginner
8 min read
Updated: Nov 2026
3 examples
java.util.Stack

Definition and Usage

A stack is a last-in, first-out (LIFO) collection: think of a pile of plates, where you add and take plates only at the top. In Java, java.util.Stack (since Java 1.0) implements this idea with push(), pop(), peek(), empty(), and search(). Stacks power the browser back button, undo in editors, bracket checking, and expression evaluation.

Stack<E> extends Vector<E>, a resizable array. The top of the stack is the last element of that array, so index 0 is the bottom. Because of the inheritance, a Stack is also a List: it allows duplicates and null, and it has index methods such as get() and remove(). The Stack Methods index lists every guide.

A legacy class with a modern replacement.

The Java documentation recommends the Deque interface, for example ArrayDeque, for new LIFO code. Stack is not deprecated and still works; you will meet it in older code, interviews, and textbooks.

Java Syntax

Stack has a single no-argument constructor. Import it from java.util:

Java
import java.util.Stack;

Stack<Integer> stack = new Stack<>();   // empty stack
stack.push(10);                            // [10]
stack.push(20);                            // [10, 20]
int top = stack.peek();                    // 20, still on the stack
int taken = stack.pop();                   // 20, stack is [10]
boolean none = stack.empty();              // false

Like Vector, a new stack has room for 10 elements and doubles its internal array when it fills up; you never manage that yourself. Calling pop() or peek() on an empty stack throws EmptyStackException.

How LIFO Works, Step by Step

Each row shows one call and the stack printed afterwards (bottom on the left, top on the right):

CallReturnsStack after
push("A")"A"[A]
push("B")"B"[A, B]
push("C")"C"[A, B, C]
peek()"C"[A, B, C] (unchanged)
search("A")3[A, B, C] (top counts as 1)
pop()"C"[A, B]

Stack vs ArrayDeque

ArrayDeque offers the same push, pop, and peek names, so switching is mostly a one-line change. The differences that matter:

TopicStackArrayDeque as a stack
Where the top isEnd of the array; prints [10, 20, 30]Front of the deque; prints [30, 20, 10]
Empty pop()EmptyStackExceptionNoSuchElementException
Empty peek()EmptyStackExceptionReturns null
null elementsAllowedNullPointerException
Index accessYes (inherited from Vector)No, only the two ends
LockingSynchronized methodsNone, so faster in one thread

The index methods are also why Stack is called a leaky design: any code can insert or remove in the middle of the "stack". A Deque<Integer> stack = new ArrayDeque<>(); exposes only the operations a stack needs at the top.

Choosing a Class for LIFO Work

TypeGood forKeep in mind
StackExisting code and textbook exercisesLegacy; synchronized calls cost a little speed
ArrayDequeNew stack and queue codeNo null, no index access
ArrayListA stack you also index heavilyUse add(e) and remove(size() - 1) yourself
LinkedListA Deque that is also a ListOne node object per element

Thread Safety

Stack inherits Vector's locking: methods like pop, peek, and search are synchronized, and push delegates to a synchronized method. Each single call is therefore safe to use from several threads. Sequences of calls are not: between empty() and pop() another thread can take the last element. Iterating with a for-each loop while another thread (or your own loop body) changes the stack usually fails with ConcurrentModificationException.

Java Examples

Example 1 — Push, Peek, Pop, and Search

A pile of three books: look at the top, take it, and ask how far down the first book is.

Java
import java.util.Stack;

public class StackBasics {
    public static void main(String[] args) {
        Stack<String> books = new Stack<>();
        books.push("Java Basics");
        books.push("Data Structures");
        books.push("Algorithms");

        System.out.println("pile: " + books);
        System.out.println("top: " + books.peek());
        System.out.println("taken: " + books.pop());
        System.out.println("pile now: " + books);
        System.out.println("Java Basics is " + books.search("Java Basics") + " from the top");
        System.out.println("empty? " + books.empty());
    }
}

How It Works

  1. Last in sits on top. Algorithms was pushed last, so it is the top; the printed list still starts with the bottom book, Java Basics.
  2. Look, then take. peek() only reads Algorithms; pop() returns the same book and removes it, leaving two books.
  3. Distance from the top. search counts the top as 1, so the bottom book of a two-book pile is 2; empty() is false because books remain.

Example 2 — Evaluate a Postfix Expression

Postfix (Reverse Polish) notation writes the operator after its two operands. A stack of numbers evaluates it in one left-to-right pass.

Java
import java.util.Stack;

public class PostfixCalculator {
    static int evaluate(String expr) {
        Stack<Integer> operands = new Stack<>();
        for (String token : expr.split(" ")) {
            if (token.equals("+") || token.equals("-") || token.equals("*")) {
                int right = operands.pop();
                int left = operands.pop();
                if (token.equals("+")) {
                    operands.push(left + right);
                } else if (token.equals("-")) {
                    operands.push(left - right);
                } else {
                    operands.push(left * right);
                }
            } else {
                operands.push(Integer.parseInt(token));
            }
        }
        return operands.pop();
    }

    public static void main(String[] args) {
        System.out.println("3 4 + = " + evaluate("3 4 +"));
        System.out.println("5 1 2 + 4 * + 3 - = " + evaluate("5 1 2 + 4 * + 3 -"));
        System.out.println("10 2 3 * - = " + evaluate("10 2 3 * -"));
    }
}

How It Works

  1. Numbers wait on the stack. Each number token is parsed and pushed, so the two most recent operands are always the top two elements.
  2. Pop order matters. For an operator the first pop() is the right operand and the second is the left one; that is why 10 2 3 * - computes 10 - 6 = 4, not 6 - 10.
  3. One value left. In 5 1 2 + 4 * + 3 - the stack goes 1 + 2 = 3, 3 * 4 = 12, 5 + 12 = 17, 17 - 3 = 14, and the final pop() returns that single result.

Example 3 — Undo Text Changes

Save a snapshot of the text before every edit. Undo pops the most recent snapshot.

Java
import java.util.Stack;

public class UndoEditor {
    public static void main(String[] args) {
        Stack<String> undo = new Stack<>();
        String text = "";

        undo.push(text);
        text = text + "Hello";
        undo.push(text);
        text = text + " World";
        undo.push(text);
        text = text + "!!!";
        System.out.println("now:    " + text);

        text = undo.pop();
        System.out.println("undo 1: " + text);
        text = undo.pop();
        System.out.println("undo 2: " + text);
        System.out.println("undo steps left: " + undo.size());
    }
}

How It Works

  1. Snapshot before editing. Each push stores the text as it was before the next change: first the empty string, then "Hello", then "Hello World".
  2. Newest snapshot first. The first pop() returns "Hello World", undoing only the "!!!" edit; the second returns "Hello".
  3. History left over. One snapshot, the empty starting text, is still on the stack, so size() reports 1 more undo step.

Next: Java Stack Methods by Group

GroupMethods
Stack operations (LIFO)push(), pop(), peek(), empty(), search()
Add and change (inherited from Vector/List)add(), addAll(), insertElementAt(), set(), setElementAt(), setSize()
Read and search (inherited from Vector/List)get(), elementAt(), firstElement(), lastElement(), indexOf(), lastIndexOf(), contains(), size(), isEmpty(), toArray()
Remove (inherited from Vector/List)remove(), removeElement(), removeElementAt(), removeAllElements(), clear()

Full list with short descriptions: Java Stack Methods index (/java/stack/method).

Frequently Asked Questions

java.util.Stack is a class that stores elements in last-in, first-out (LIFO) order. push puts an element on top, pop removes the top, and peek reads the top without removing it. It extends Vector and has been part of Java since version 1.0.
No, it is not deprecated and still works. It is considered a legacy class: the Java documentation recommends a Deque such as ArrayDeque for new LIFO code because Deque offers a cleaner, more complete set of stack operations.
Stack stores its elements in a Vector with the top at the end, and Vector prints in index order. So [10, 20, 30] means 30 is the top. An ArrayDeque used as a stack prints the top first: [30, 20, 10].
Its methods are synchronized through Vector, so a single call such as push or pop is safe from several threads. A check followed by an action, like if (!stack.empty()) stack.pop(), is still two calls and needs your own locking. For concurrent code, java.util.concurrent offers better tools.
pop() and peek() throw EmptyStackException, an unchecked exception from java.util. Check empty() or isEmpty() first, or catch the exception.

Browse every Stack method

Open the methods index for categorized guides with examples and FAQs.

Stack Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful