In Java, pop()removes the top element of a Stack and returns it. The top is the element pushed most recently, so a series of pops hands elements back in the reverse of the order they were pushed.
Use pop when you are done with the top element, for example to go back one page or undo one action. If you only want to look at it, use peek() instead. Calling pop on an empty stack throws EmptyStackException.
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 pop with no arguments; it returns the removed top element.
Java
Stack<String> stack = new Stack<>();
stack.push("a");
stack.push("b");
String top = stack.pop(); // "b", stack is [a]
stack.pop(); // "a", stack is []
stack.pop(); // throws EmptyStackException
Call
What it does
stack.pop()
Removes and returns the top element.
while (!stack.empty()) stack.pop()
Takes every element, top first.
stack.peek()
Returns the top without removing it.
stack.remove(stack.size() - 1)
The same removal through the List API; fails with an index exception when empty.
pop runs in constant time: it reads the last element of the internal array and lowers the size by one. The array itself does not shrink.
Library declarations
Java
// java.util.Stack<E>
public synchronized E pop()
// throws java.util.EmptyStackException if the stack is empty
Parameters
Parameter
Description
None
pop() takes no parameters.
Return Value
Return Value
Description
E
The element that was on top. It can be null if null was pushed.