In Java, isEmpty() returns true when a Stack holds no elements and false otherwise. It is declared in the Collection interface and inherited through Vector.
Stack also has its own empty(), which gives the same answer. isEmpty() is the name every Java collection understands, so use it whenever your code works with a List or Collection rather than a Stack.
An instance method inherited from java.util.Vector (since Java 1.0). Stack does not override it: index 0 is the bottom of the stack and index size() - 1 is the top.
Syntax
Call isEmpty with no arguments.
Java
Stack<String> stack = new Stack<>();
boolean a = stack.isEmpty(); // true
stack.push("x");
boolean b = stack.isEmpty(); // false
boolean c = stack.empty(); // false: the same answer, Stack-only name
Call
What it does
stack.isEmpty()
true when there are no elements.
!stack.isEmpty()
true when there is something to pop or peek.
stack.empty()
Stack's own name for the same check.
collection.isEmpty()
Works for any List, Set, Queue, or Stack.
isEmpty is constant time.
Library declarations
Java
// java.util.Vector<E>, inherited by Stack<E>
public synchronized boolean isEmpty()
// declared in java.util.Collection<E>
holding null, isEmpty: false, size 1
after clear, isEmpty: true, empty: true
safe check on null variable: true
How It Works
null is still an element. A stack holding one null has size 1, so isEmpty() is false.
clear() empties for real. After clear(), both isEmpty() and Stack's empty() are true.
A null variable is different.missing refers to no stack at all; || short-circuits on missing == null, so isEmpty() is never called on it and no NullPointerException occurs.
Frequently Asked Questions
true if the stack has no elements, false if it has at least one.
Both give the same result. isEmpty() works on every collection, so it is the better habit; empty() exists only on Stack.
No. A null element counts, so size() is 1 and isEmpty() is false.
They do the same work: both read the element count, which takes constant time.
Not on a real stack. Calling any method through a variable that is null throws NullPointerException, so check the variable first if it may be null.