In Java, pop() removes the element on top of a stack and returns it. An ArrayDeque keeps the top at its head, so pop() is the same as removeFirst().
It pairs with push(e): the last element pushed is the first popped. If the stack is empty, pop() throws NoSuchElementException. (The legacy Stack class throws EmptyStackException instead.)
An instance method of java.util.ArrayDeque (Java 1.6+): a resizable-array deque with no capacity limit, no null elements, and no thread safety.
Syntax
Call pop with no arguments to remove the top.
Java
Deque<String> stack = new ArrayDeque<>();
stack.push("a");
stack.push("b");
String top = stack.pop(); // "b", stack = [a]
Call
What it does
stack.pop()
Removes and returns the top; throws if empty.
stack.removeFirst()
Exactly the same operation.
stack.poll()
Also removes the head, but returns null when empty.
stack.peek()
Reads the top without removing it.
If you want a stack that returns null instead of throwing, use poll(), which removes from the same end. Many programs simply guard pop() with isEmpty().
Library declarations
Java
// java.util.ArrayDeque<E>
public E pop()
// Declared in Deque<E>
Parameters
Parameter
Description
None
pop() takes no parameters.
Return Value
Return Value
Description
E
The element at the top of the stack (the head).
Throw or Return a Special Value?
Each end has a method that throws when it cannot work (such as on an empty deque) and one that returnsnull or false instead. The highlighted cell matches pop().