peek: Inspecting the Top Element
What you'll learn: How to look at the top element of a stack without removing it using the peek method.
What Is peek?
When using a Deque as a stack, sometimes you need to see what's on top without actually removing it. That's exactly what peek() does — it returns the top element (the most recently pushed item) but leaves the stack unchanged.
Think of it like looking at the top card in a deck without picking it up. You can see what it is, but the deck remains exactly as it was.
How peek Works
The peek() method:
- Returns the element at the top of the stack (head of the deque)
- Does not remove the element
- Returns
nullif the stack is empty (instead of throwing an exception)
Deque<String> stack = new ArrayDeque<>();
stack.push("First");
stack.push("Second");
stack.push("Third");
String top = stack.peek(); // Returns "Third"
System.out.println(top); // Prints: Third
System.out.println(stack.peek()); // Still "Third"
System.out.println(stack.peek()); // Still "Third"
// The stack still has all three elements
System.out.println(stack.size()); // Prints: 3
Return Behavior on Empty Stack
Unlike pop(), which throws an exception when the stack is empty, peek() gracefully returns null:
Deque<String> emptyStack = new ArrayDeque<>();
String result = stack.peek(); // Returns null, no exception
if (result == null) {
System.out.println("Stack is empty");
}
This makes peek() safer for checking if a stack has elements before performing operations.
Key Takeaway: Use peek() to inspect the top element of a stack without removing it; it returns null for empty stacks instead of throwing an exception, making it ideal for safe, non-destructive inspection.