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
- Check isEmpty() before each peek() call.
- Seed the stack with a sentinel value so it is never empty during traversal.
- Refactor the loop guard to terminate on isEmpty() rather than a separate size counter.
- 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
- Guard peek() with isEmpty() when an empty stack is possible.
- Seed sentinels in algorithms that must always peek.
- Use isEmpty() as the loop terminator.
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
- Cannot pop from an empty stack.
- Stack is empty, cannot pop element
- Stack is empty, cannot peek element
- Empty stack. Nothing to pop
- Empty stack. Nothing to peek
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/3450b14f2faf1325.
Report an issue: GitHub.