In Java, empty()tests whether a Stack has no elements. It returns true when there is nothing to pop and false otherwise.
It is the standard loop condition for stack algorithms: while (!stack.empty()) keeps popping until the stack is drained. Stack also inherits isEmpty() from Vector, which always gives the same answer.
Declared in java.util.Stack itself (since Java 1.0). Stack<E> extends Vector<E> and keeps the top at the end of the vector, so printing a stack lists it from bottom to top.
Syntax
Call empty with no arguments; it only reads the size.
Java
Stack<Integer> stack = new Stack<>();
boolean a = stack.empty(); // true
stack.push(1);
boolean b = stack.empty(); // false
stack.pop();
boolean c = stack.empty(); // true again
Call
What it does
stack.empty()
true when the size is 0.
while (!stack.empty()) stack.pop()
Pops everything, top first.
stack.isEmpty()
Same result; declared in Collection and inherited from Vector.
stack.size() == 0
Same result written by hand.
empty() runs in constant time: it compares the element count with zero.
Two names, one answer. In every state, Stack's own empty() and the inherited isEmpty() print the same value.
Both follow the size. They are true exactly when size() is 0: before the push and after the pop.
A null element still counts. After push(null) the stack holds one element, so neither method calls it empty.
Example 3 — Disable Undo When There Is Nothing to Undo
An undo() method checks empty() so extra clicks never crash the program.
Java
import java.util.Stack;
public class StackEmptyUndoGuard {
static Stack<String> history = new Stack<>();
static void undo() {
if (history.empty()) {
System.out.println("Nothing to undo");
} else {
System.out.println("Undid: " + history.pop());
}
}
public static void main(String[] args) {
history.push("draw circle");
undo();
undo();
history.push("draw square");
undo();
}
}
Output
Undid: draw circle
Nothing to undo
Undid: draw square
How It Works
Check before acting.undo() asks history.empty() first, so the pop only happens when there is an action to reverse.
A second click is harmless. After "draw circle" is undone the history is empty, and the second call prints a message instead of throwing EmptyStackException.
Works again after a push. Drawing a square refills the history, so the third call finds that action and pops it.
Frequently Asked Questions
true if the stack has no elements, false if it has at least one.
They return the same result. empty() is declared in Stack since Java 1.0; isEmpty() comes from Collection through Vector and also works on lists, sets, and queues.
Yes, unless you prefer to catch EmptyStackException. A while (!stack.empty()) loop is the usual way to pop everything.
No. null is an element like any other, so a stack holding one null has size 1 and empty() returns false.
No. ArrayDeque and the other collections use isEmpty(). Only Stack has the extra empty() method.