In Java, peek()returns the top element of a Stack and leaves it where it is. Calling it twice in a row returns the same element.
peek is how stack algorithms make decisions: look at the top, then decide whether to pop, push, or stop. On an empty stack it throws EmptyStackException, unlike ArrayDeque.peek(), which returns null.
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 peek with no arguments; the stack is not modified.
Java
Stack<String> stack = new Stack<>();
stack.push("first");
stack.push("second");
String top = stack.peek(); // "second", stack still [first, second]
String again = stack.peek(); // "second" again
new Stack<String>().peek(); // throws EmptyStackException
Call
What it does
stack.peek()
The top element; the stack is unchanged.
stack.empty() ? null : stack.peek()
A peek that gives null instead of throwing.
stack.lastElement()
Vector's name for the same element; throws NoSuchElementException when empty.
stack.get(stack.size() - 1)
The same element through the List API.
peek takes constant time: it reads the last element of the internal array.
Library declarations
Java
// java.util.Stack<E>
public synchronized E peek()
// throws java.util.EmptyStackException if the stack is empty
Parameters
Parameter
Description
None
peek() takes no parameters.
Return Value
Return Value
Description
E
The top element, the one pushed most recently. It can be null if null was pushed.
Openers are pushed. Every (, [, or { goes on the stack, so the most recent unclosed bracket is always on top.
Peek before popping. A closing bracket must match the opener that peek() shows; in ([)] the top is [ when ) arrives, so the method returns false without touching the stack.
Leftovers mean unbalanced. In ((x) one ( is never closed, so the final open.empty() is false; letters such as x are simply skipped.
Example 3 — Peek at an Empty Stack
Compare a helper that checks first, ArrayDeque.peek(), and a bare Stack.peek() on empty collections.