TheAlgorithms/Java · error · IllegalStateException

Stack is empty, cannot peek element

Error message

Stack is empty, cannot peek element

What it means

Thrown by StackArray.peek() when the stack is empty. peek() returns stackArray[top]; with top==-1 this would index out of bounds. The IllegalStateException enforces the precondition that a top element must exist before inspection.

Source

Thrown at src/main/java/com/thealgorithms/datastructures/stacks/StackArray.java:87

            throw new IllegalStateException("Stack is empty, cannot pop element");
        }
        T value = stackArray[top--];
        if (top + 1 < maxSize / 4 && maxSize > DEFAULT_CAPACITY) {
            resize(maxSize / 2);
        }
        return value;
    }

    /**
     * Returns the element at the top of the stack without removing it.
     *
     * @return the top element of the stack
     * @throws IllegalStateException if the stack is empty
     */
    @Override
    public T peek() {
        if (isEmpty()) {
            throw new IllegalStateException("Stack is empty, cannot peek element");
        }
        return stackArray[top];
    }

    /**
     * Resizes the internal array to a new capacity.
     *
     * @param newSize the new size of the stack array
     */
    private void resize(int newSize) {
        @SuppressWarnings("unchecked") T[] newArray = (T[]) new Object[newSize];
        System.arraycopy(stackArray, 0, newArray, 0, top + 1);
        stackArray = newArray;
        maxSize = newSize;
    }

    /**
     * Checks if the stack is full.

View on GitHub (pinned to fdfb9a395b)

Solutions

  1. Guard every peek() with isEmpty().
  2. Push a sentinel element so the stack is never empty during the peek window.
  3. Terminate the consuming loop on isEmpty() rather than an external counter.
  4. Catch IllegalStateException if empty-peek is a valid control-flow branch.

Example fix

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

Strategy: validation

Validate before calling

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

Prevention

When it happens

Trigger: Calling peek() on a new StackArray. Calling peek() after the stack has been fully drained. Inspecting the top before the first push in an algorithm.

Common situations: Monotonic-stack or parsing algorithms that peek before seeding. Stateful processing where the first iteration peeks an uninitialized stack. Loops with off-by-one bounds.

Related errors


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