TheAlgorithms/Java · error · NoSuchElementException

Stack is empty

Error message

Stack is empty

What it means

GreatestElementConstantTime maintains a main stack plus an auxiliary maxStack to report the maximum in O(1). pop() removes the top of mainStack and, if that element equals the current maximum, also pops maxStack. Calling pop() when the stack is empty would underflow both stacks, so it throws java.util.NoSuchElementException with message 'Stack is empty'.

Source

Thrown at src/main/java/com/thealgorithms/stacks/GreatestElementConstantTime.java:54

            return;
        }

        mainStack.push(data);
        if (data > maxStack.peek()) {
            maxStack.push(data);
        }
    }

    /**
     * Pops an element from the stack.
     * Checks if the element to be popped is the maximum or not
     * If so, then pop from the minStack
     *
     * @throws NoSuchElementException if the stack is empty.
     */
    public void pop() {
        if (mainStack.isEmpty()) {
            throw new NoSuchElementException("Stack is empty");
        }

        int ele = mainStack.pop();
        if (ele == maxStack.peek()) {
            maxStack.pop();
        }
    }

    /**
     * Returns the maximum element present in the stack
     *
     * @return The element at the top of the maxStack, or null if the stack is empty.
     */
    public Integer getMaximumElement() {
        if (maxStack.isEmpty()) {
            return null;
        }
        return maxStack.peek();

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Guard every pop() with an isEmpty()/size check.
  2. Track the count of pushed elements and never pop beyond it.
  3. Catch NoSuchElementException at call sites where emptiness is an expected runtime condition.

Example fix

// before
while (!stack.getMaximum().equals(target)) {
    stack.pop(); // throws when drained
}

// after
while (!stack.isEmpty() && !stack.getMaximum().equals(target)) {
    stack.pop();
}
Defensive patterns

Strategy: validation

Validate before calling

static void safePop(GreatestElementConstantTime s) {
    if (s.isEmpty()) {            // requires an isEmpty()/size() accessor
        throw new IllegalStateException("cannot pop: stack is empty");
    }
    s.pop();
}

Try / catch

try {
    stack.pop();
} catch (java.util.NoSuchElementException e) {
    // expected when the stack was already drained; recover or ignore
}

Prevention

When it happens

Trigger: Calling `.pop()` more times than elements were pushed, or calling pop() on a freshly-constructed (empty) instance. Note: getMaximum on an empty stack returns null rather than throwing, so the asymmetry can surprise callers.

Common situations: Mismatched push/pop counts in a loop; draining logic that pops in a while-true without an isEmpty guard; popping during error/cleanup paths that run even when nothing was pushed; concurrent/recursive code that pops past its push depth.

Related errors


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