Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Deque.pop()

Removes and returns the element at the top of a stack.

Available since: Java 1.6

Syntax

E pop()

Return value

EThe element from the top of the stack.

Examples

A browser Back button:

void main() {
    Deque<String> history = new ArrayDeque<>(List.of("product", "catalog", "home"));
    IO.println(history.pop());
    IO.println(history.pop());
    IO.println(history);
}

Output:

product
catalog
[home]

An empty stack:

void main() {
    Deque<String> stack = new ArrayDeque<>();
    try {
        stack.pop();
    } catch (NoSuchElementException e) {
        IO.println("Stack is empty");
    }
    IO.println(stack.poll());
}

Output:

Stack is empty
null

Notes

pop() on an empty stack throws NoSuchElementException, while poll() returns null. If an empty stack is a normal situation, use poll() or check isEmpty() first.

See also

  • Deque.push() — Pushes an element onto the top of a stack (the head of a deque).
  • Queue.poll() — Takes and removes the head of a queue.
  • ArrayDeque — A fast array-based double-ended queue — a replacement for `Stack` and `LinkedList`.

In the tutorial

  • Queues and deques — Queues in Java: Queue and ArrayDeque, a stack built on Deque, the offer, poll and peek methods and the PriorityQueue.

Thanks for reading!

Donate to the site — we work hard for you.