TheAlgorithms/Java · error · IllegalStateException

Cannot peek from an empty stack.

Error message

Cannot peek from an empty stack.

What it means

Thrown by NodeStack.peek() when the stack has no elements. peek() returns head.data without removing the node, so an empty stack would cause a NullPointerException. The IllegalStateException is a precondition violation: you are inspecting a top that does not exist.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/stacks/NodeStack.java:76

    public Item pop() {
        if (isEmpty()) {
            throw new IllegalStateException("Cannot pop from an empty stack.");
        }
        Item data = head.data;
        head = head.previous;
        size--;
        return data;
    }

    /**
     * Returns the item at the top of the stack without removing it.
     *
     * @return the item at the top of the stack, or {@code null} if the stack is empty
     * @throws IllegalStateException if the stack is empty
     */
    public Item peek() {
        if (isEmpty()) {
            throw new IllegalStateException("Cannot peek from an empty stack.");
        }
        return head.data;
    }

    /**
     * Checks whether the stack is empty.
     *
     * @return {@code true} if the stack has no elements, {@code false} otherwise
     */
    public boolean isEmpty() {
        return head == null;
    }

    /**
     * Returns the number of elements currently in the stack.
     *
     * @return the size of the stack
     */

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Check isEmpty() before each peek() call.
  2. Seed the stack with a sentinel value so it is never empty during traversal.
  3. Refactor the loop guard to terminate on isEmpty() rather than a separate size counter.
  4. Catch IllegalStateException if an empty peek is an expected branch in your control flow.

Example fix

// before
Item top = stack.peek();
// after
Item top = stack.isEmpty() ? null : stack.peek();
Defensive patterns

Strategy: validation

Validate before calling

Item top = stack.isEmpty() ? null : stack.peek();

Prevention

When it happens

Trigger: Calling peek() on a newly created NodeStack. Calling peek() after the stack has been drained by pops. Inspecting the top inside a loop whose exit condition is based on an external counter rather than isEmpty().

Common situations: Implementing algorithms (e.g., parentheses matching, monotonic-stack problems) where the first peek happens before any push. Stateful parsers that peek before pushing a sentinel. Off-by-one in loop bounds causing one extra peek.

Related errors


AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13). Data as JSON: /api/errors/3450b14f2faf1325. Report an issue: GitHub.