01 / 21

Java Queue
Interface

Master FIFO patterns using the Queue interface: offer, poll, and peek for clean, predictable data processing.

Java

What Is a Queue?

A Queue is a data structure that follows the First-In, First-Out (FIFO) principle. The element added first is the element removed first: like a line of people at a ticket counter.

A B C D offer() poll() FRONT REAR

The Queue Interface in Java

In Java, Queue is an interface in the java.util package. It extends Collection and defines the contract for FIFO behavior. You cannot instantiate it directly: you must use an implementing class.

import java.util.Queue; import java.util.LinkedList; Queue<String> line = new LinkedList<>();

Why Use a Queue?

★ Task Scheduling
Process jobs in the order they arrive: print queues, thread pools, message brokers.
★ BFS Traversal
Breadth-first search on graphs and trees requires a queue to explore neighbors level by level.
★ Buffering
Smooth data flow between producer and consumer at different speeds: I/O buffers, streaming.

Core Methods: offer, poll, peek

offer(e)
Inserts element e at the rear. Returns true on success, false if capacity is full.
poll()
Removes and returns the front element. Returns null if the queue is empty.
peek()
Returns the front element without removing it. Returns null if the queue is empty.

Throwing vs. Non-Throwing Methods

Operation Throws Exception Returns null/false
Insert add(e) offer(e)
Remove remove() poll()
Examine element() peek()

Queue vs. Stack vs. List

Feature Queue Stack List
Order FIFO LIFO Indexed
Insert offer (rear) push (top) add (any index)
Remove poll (front) pop (top) remove (any index)
Inspect peek (front) peek (top) get (any index)
Random Access No No Yes

How to Apply the Queue Pattern

1
Declare the variable as Queue<T>. Program to the interface, not the implementation.
2
Instantiate with LinkedList or ArrayDeque. ArrayDeque is generally faster; LinkedList supports null elements.
3
Enqueue with offer(e). Add elements to the rear of the queue.
4
Process with a while loop. Use while (!queue.isEmpty()) and call poll() each iteration.
5
Inspect without removing using peek(). Check the front element before deciding to process.

Example 1: Basic Operations

Queue<String> q = new LinkedList<>(); q.offer("Alice"); q.offer("Bob"); q.offer("Carol"); System.out.println(q.peek()); // "Alice" System.out.println(q.poll()); // "Alice" System.out.println(q.poll()); // "Bob" System.out.println(q.peek()); // "Carol"
After 3 offers: Alice Bob Carol After poll() + poll(): Carol peek() returns front without removing: Carol peek() → "Carol"

Example 2: Processing Loop

A common pattern is to drain a queue with a while loop, processing each element in FIFO order:

Queue<Integer> tasks = new LinkedList<>(); tasks.offer(10); tasks.offer(20); tasks.offer(30); while (!tasks.isEmpty()) { int task = tasks.poll(); System.out.println("Processing: " + task); } // Output: Processing: 10, 20, 30 (FIFO order)

Example 3: BFS with a Queue

Breadth-First Search (BFS) is the classic queue application. The queue ensures nodes are visited level by level.

public void bfs(Node start) { Queue<Node> q = new LinkedList<>(); Set<Node> visited = new HashSet<>(); q.offer(start); visited.add(start); while (!q.isEmpty()) { Node current = q.poll(); process(current); for (Node neighbor : current.neighbors()) { if (!visited.contains(neighbor)) { visited.add(neighbor); q.offer(neighbor); } } } }

Visualizing BFS Order

A Level 0 B C Level 1 D E F G Level 2 Queue poll order: A → B → C → D → E → F → G

ArrayDeque vs. LinkedList

Feature ArrayDeque LinkedList
Underlying structure Resizable array Doubly linked list
Null elements Not allowed Allowed
Memory overhead Lower (contiguous) Higher (node objects)
Performance Faster (cache friendly) Slower (pointer chasing)
Thread-safe No No

Queue Inside the Deque Hierarchy

Collection<E> Queue<E> Deque<E> LinkedList<E> ArrayDeque<E>

Common Mistakes

✕ Using add/remove
Using add() and remove() instead of offer/poll leads to uncaught exceptions on full or empty queues.
✕ Polling Without Check
Calling poll() and using the result without checking for null causes NullPointerExceptions downstream.
✕ Wrong Implementation
Using PriorityQueue thinking it's FIFO. PriorityQueue orders by natural ordering or a comparator, not arrival time.

Queue Cheat Sheet

Method Action On Empty / Full Time
offer(e) Insert at rear Returns false \(O(1)\)
poll() Remove from front Returns null \(O(1)\)
peek() View front Returns null \(O(1)\)
isEmpty() Check if empty Returns true \(O(1)\)
size() Count elements Returns 0 \(O(1)\)

Question 1 of 5

Which method removes and returns the front element of a Queue, returning null if the queue is empty?

Question 2 of 5

What does the following code print?

Queue<Integer> q = new LinkedList<>(); q.offer(5); q.offer(10); q.offer(15); q.poll(); System.out.println(q.peek());

Question 3 of 5

Which Queue implementation does the Java documentation recommend as the default choice?

Question 4 of 5

Why is PriorityQueue NOT suitable when you need strict FIFO ordering?

Question 5 of 5

What is the correct pattern to safely process all elements in a Queue?