Queue in Java
Master the Queue interface in Java: FIFO semantics, dual-method API, key implementations, and how to pick the right queue for your use case.
Queue<E> is a Collection sub-interface that models a sequence of elements where insertions happen at the tail and removals happen at the head — the classic First-In-First-Out (FIFO) ordering. Queues are used everywhere: task schedulers, breadth-first search, producer-consumer pipelines, and rate-limiting buffers. The Queue interface deliberately defines a dual set of methods — one that throws exceptions and one that returns special values — so you can choose the behaviour that best fits your context.
The Queue Interface
Queue<E> extends Collection<E> and defines three operations, each available in two forms:
| Operation | Throws exception | Returns special value |
|---|---|---|
| Insert | add(e) — throws IllegalStateException if full |
offer(e) — returns false if full |
| Remove | remove() — throws NoSuchElementException if empty |
poll() — returns null if empty |
| Examine (peek) | element() — throws NoSuchElementException if empty |
peek() — returns null if empty |
In practice, prefer offer, poll, and peek for most code. The throwing variants (add, remove, element) are useful when an empty or full queue represents a programming error that should be surfaced immediately.
Key Queue Implementations
| Implementation | Ordering | Bounded | Thread-safe | Null |
|---|---|---|---|---|
ArrayDeque |
FIFO | No | No | No |
LinkedList |
FIFO | No | No | Yes |
PriorityQueue |
Natural/Comparator order | No | No | No |
ArrayBlockingQueue |
FIFO | Yes | Yes | No |
LinkedBlockingQueue |
FIFO | Optional | Yes | No |
ConcurrentLinkedQueue |
FIFO | No | Yes (lock-free) | No |
ArrayDeque is the preferred Queue implementation for single-threaded FIFO use because it is backed by a circular resizable array with no per-node allocation overhead.
Example 1: Queue Operations with ArrayDeque
import java.util.ArrayDeque;
import java.util.Queue;
public class QueueBasics {
public static void main(String[] args) {
Queue<String> queue = new ArrayDeque<>();
// Enqueue (insert at tail)
queue.offer("Alice");
queue.offer("Bob");
queue.offer("Charlie");
System.out.println("Queue: " + queue); // [Alice, Bob, Charlie]
// Peek (examine head without removing)
System.out.println("Head: " + queue.peek()); // Alice
// Dequeue (remove from head — FIFO)
System.out.println("Poll: " + queue.poll()); // Alice
System.out.println("Poll: " + queue.poll()); // Bob
System.out.println("Queue: " + queue); // [Charlie]
// poll() on empty queue returns null — does not throw
queue.poll(); // removes Charlie
System.out.println("Empty poll: " + queue.poll()); // null (not an exception)
}
}
Example 2: BFS with a Queue
Breadth-first search (BFS) is one of the canonical uses of a queue. Elements at the current level are processed before elements at the next level.
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
public class BFSExample {
public static List<Integer> bfs(Map<Integer, List<Integer>> graph, int start) {
List<Integer> order = new ArrayList<>();
Set<Integer> visited = new HashSet<>();
Queue<Integer> queue = new ArrayDeque<>();
queue.offer(start);
visited.add(start);
while (!queue.isEmpty()) {
int node = queue.poll();
order.add(node);
for (int neighbour : graph.getOrDefault(node, List.of())) {
if (visited.add(neighbour)) { // add returns false if already present
queue.offer(neighbour);
}
}
}
return order;
}
public static void main(String[] args) {
Map<Integer, List<Integer>> graph = new HashMap<>();
graph.put(1, List.of(2, 3));
graph.put(2, List.of(4));
graph.put(3, List.of(4, 5));
graph.put(4, List.of());
graph.put(5, List.of());
System.out.println(bfs(graph, 1)); // [1, 2, 3, 4, 5]
}
}
Common Mistakes
- Using
remove()orelement()instead ofpoll()andpeek()when the queue might be empty.remove()andelement()throwNoSuchElementExceptionon an empty queue. Usepoll()andpeek()and check fornullinstead. - Using
LinkedListas a queue whenArrayDequeis available.LinkedListallocates a node object per element;ArrayDequeuses a backing array with better cache performance. Unless you specifically neednullelements in the queue or theListinterface, preferArrayDeque. - Assuming
Queueis ordered. MostQueueimplementations are FIFO, butPriorityQueueorders by priority, not insertion order. If you need guaranteed FIFO, avoidPriorityQueue. - Ignoring the return value of
offer.offerreturnsfalseif the element could not be added (e.g., a boundedArrayBlockingQueueis full). Ignoring this can silently drop work items. - Using
for-eachto process a queue while adding elements. Modifying aQueueinside a for-each loop throwsConcurrentModificationException. Use awhile (!queue.isEmpty())loop withpoll()instead.
Best Practices
- Declare the type as
Queue<E>, notArrayDeque<E>, to keep the implementation swappable. - Use
offer/poll/peek(the null-returning variants) in application code; reserve the throwing variants for internal assertion checks. - For producer-consumer scenarios, use
BlockingQueueimplementations (LinkedBlockingQueue,ArrayBlockingQueue) fromjava.util.concurrent. - For lock-free concurrent queuing, use
ConcurrentLinkedQueue. - In BFS and other graph algorithms, use
ArrayDeque— it is the fastest general-purpose queue implementation.
Interview Questions
1. What is the Queue interface in Java?
Queue<E> is a Collection sub-interface for FIFO element storage. It adds offer/poll/peek (null-returning) and add/remove/element (exception-throwing) methods. Most implementations process elements in insertion order, though PriorityQueue is an exception that orders by priority.
2. What is the difference between offer and add in Queue?
Both insert an element at the tail of the queue. add throws IllegalStateException if the element cannot be added (relevant for bounded queues). offer returns false instead. For unbounded queues like ArrayDeque, they behave identically, but offer is the conventional choice.
3. What is the difference between poll and remove?
Both remove and return the head of the queue. poll returns null if the queue is empty; remove throws NoSuchElementException. Similarly, peek returns null for empty queues while element throws.
4. Why is ArrayDeque preferred over LinkedList as a Queue?
ArrayDeque stores elements in a circular resizable array. Compared to LinkedList, it avoids per-element Node object allocation, has better CPU cache locality (contiguous memory), and therefore performs better in practice for both enqueue and dequeue operations. ArrayDeque also does not allow null elements, which avoids ambiguity with poll's null return on an empty queue.
5. What is a blocking queue and when would you use it?
A BlockingQueue (from java.util.concurrent) adds methods that block the calling thread: put(e) blocks if the queue is full, and take() blocks if the queue is empty. This makes BlockingQueue the right tool for producer-consumer patterns where producers and consumers run on separate threads and need to synchronise naturally without explicit locks.
6. How does a queue relate to BFS?
Breadth-first search uses a queue to ensure that nodes closer to the start node are processed before nodes farther away. You enqueue the start node, then repeatedly dequeue a node, process it, and enqueue all its unvisited neighbours. The FIFO property of the queue guarantees level-by-level traversal.
7. Can you add null to an ArrayDeque queue?
No. ArrayDeque does not permit null elements; offer(null) throws NullPointerException. This is intentional: poll() and peek() return null to signal an empty queue, so allowing null as a value would create ambiguity. If you need null elements, use LinkedList as a Queue, but this is rare.
Summary
Queue<E>models FIFO element storage with a dual API: exception-throwing (add,remove,element) and null-returning (offer,poll,peek).ArrayDequeis the preferredQueueimplementation for single-threaded code.PriorityQueueis an important exception — it orders by priority, not insertion order.- Use
java.util.concurrentblocking and concurrent queues for multi-threaded producer-consumer scenarios. - BFS traversal is the classic algorithmic use case for a queue.
Continue Learning
Was this guide helpful?
CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.