Java Stack peek() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Stack method

Definition

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
CallWhat 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

ParameterDescription
Nonepeek() takes no parameters.

Return Value

Return ValueDescription
EThe top element, the one pushed most recently. It can be null if null was pushed.

Compare with Similar Methods

Ways to read the ends of a stack:

MethodHow it differs
pop()Returns the top and removes it.
lastElement()Same element; throws NoSuchElementException instead of EmptyStackException.
firstElement()Reads the other end: the bottom.
ArrayDeque.peek()Returns null on an empty deque instead of throwing.

Java Examples

Example 1 — Read the Top Ticket Without Taking It

A kitchen spike holds order tickets; the cook looks at the top ticket before serving it.

Java
import java.util.Stack;

public class StackPeekOrders {
    public static void main(String[] args) {
        Stack<String> tickets = new Stack<>();
        tickets.push("soup");
        tickets.push("pasta");
        tickets.push("salad");

        System.out.println("on top: " + tickets.peek());
        System.out.println("still on top: " + tickets.peek());
        System.out.println("tickets: " + tickets.size());

        String served = tickets.pop();
        System.out.println("served " + served + ", next up: " + tickets.peek());
    }
}

How It Works

  1. Peek is read-only. Two peek() calls both return salad, the last ticket pushed, and the count stays at 3.
  2. Pop takes that same ticket. pop() returns salad too, but this time it leaves the stack.
  3. The next ticket shows. After the pop, peek() reveals pasta, the ticket that was underneath.

Example 2 — Check Balanced Brackets

The classic stack exercise: every closing bracket must match the most recent unclosed opening bracket.

Java
import java.util.Stack;

public class StackPeekBrackets {
    static boolean isBalanced(String text) {
        Stack<Character> open = new Stack<>();
        for (char c : text.toCharArray()) {
            if (c == '(' || c == '[' || c == '{') {
                open.push(c);
            } else if (c == ')' || c == ']' || c == '}') {
                if (open.empty()) {
                    return false;
                }
                char top = open.peek();
                boolean match = (top == '(' && c == ')')
                        || (top == '[' && c == ']')
                        || (top == '{' && c == '}');
                if (!match) {
                    return false;
                }
                open.pop();
            }
        }
        return open.empty();
    }

    public static void main(String[] args) {
        String[] inputs = {"{[()]}", "([)]", "((x)", "a(b)c"};
        for (String s : inputs) {
            System.out.println(s + " -> " + isBalanced(s));
        }
    }
}

How It Works

  1. Openers are pushed. Every (, [, or { goes on the stack, so the most recent unclosed bracket is always on top.
  2. 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.
  3. 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.

Java
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.EmptyStackException;
import java.util.Stack;

public class StackPeekEmpty {
    static String peekOrNull(Stack<String> s) {
        return s.empty() ? null : s.peek();
    }

    public static void main(String[] args) {
        Stack<String> stack = new Stack<>();
        Deque<String> deque = new ArrayDeque<>();

        System.out.println("helper: " + peekOrNull(stack));
        System.out.println("ArrayDeque.peek(): " + deque.peek());
        try {
            stack.peek();
        } catch (EmptyStackException e) {
            System.out.println("Stack.peek(): " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Helper checks first. peekOrNull calls empty() before peek(), so an empty stack yields null instead of an exception.
  2. ArrayDeque returns null. Deque.peek() is designed to return null when there is nothing to show.
  3. Stack throws. The bare stack.peek() on an empty stack throws EmptyStackException, which the catch block reports by class name.

Frequently Asked Questions

It returns the top element, the one pushed most recently, without removing it. The stack is unchanged.
No. Stack.peek() throws EmptyStackException when the stack is empty. ArrayDeque.peek() returns null instead.
peek() only reads the top element. pop() reads it and removes it.
They return the same element. On an empty stack peek() throws EmptyStackException and lastElement() throws NoSuchElementException.
A Stack prints from bottom to top, so the top element, which peek() returns, is the rightmost one.

Next: pop()

Remove the top element and return it.

pop() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful