Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Queue.poll() — retrieve and remove the head of a queue

`Queue.poll()` retrieves and removes the head of a queue. If the queue is empty, it returns `null` rather than throwing an exception.

Version: Java SE 21

Syntax

E poll();
// Call on a Queue<E> instance:
E head = queue.poll();

Queue.poll() is a no-argument method of java.util.Queue<E>. It returns the head element as type E and removes it from the queue. If the queue is empty, the method returns null without waiting for an element to be added.

The queue implementation determines which element is at the head. In the example, ArrayDeque adds elements at the tail with offer() and removes them from the head with poll(), so the order is FIFO: first in, first out. Not every queue uses this order.

peek() returns the head without removing it, or returns null if the queue is empty. The no-argument remove() returns and removes the head, but throws NoSuchElementException if the queue is empty.

Avoid storing null as a queue element, even if the implementation allows it: a null result alone then cannot distinguish an empty queue from the removal of a null element. ArrayDeque does not allow null elements.

Examples

import java.util.ArrayDeque;
import java.util.Queue;

public class Main {
    public static void main(String[] args) {
        Queue<String> queue = new ArrayDeque<>();
        queue.offer("A");
        queue.offer("B");

        System.out.println(queue.peek());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
    }
}

Result

A
A
B
null

The first `A` comes from `peek()`, which leaves the element in the queue. The next two `poll()` calls remove `A` and then `B`. The final call returns `null` because the queue is now empty.

Related lessons

  • Java · Lesson 61 · Basic · Version: 2

Sources