Queues: first in, first out
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A queue is a linear data structure that follows the First-In First-Out principle. The first element added is always the first element removed.
The FIFO principle: offer, poll and peek
A queue is a collection where the first element added is the first one removed (FIFO), adding at the back and removing from the front.
A queue enforces First-In, First-Out (FIFO) ordering, ensuring items are processed in the exact order they arrive. A proper queue uses independent front and rear pointers, allowing both enqueue and dequeue to run in O(1) time.
int[] data = new int[10];int front = 0, rear = 0; // two independent pointersdata[rear++] = 100; // enqueue at the reardata[rear++] = 200;int first = data[front++]; // dequeue from the front: 100 (first in, first out)Why not use a standard array where dequeue removes index 0? Removing index 0 from a regular array forces all remaining elements to shift left by one position. Shifting n elements takes O(n) time per dequeue, degrading 100,000 queue operations into 10 billion operations. Trace FIFO queue operations: Start with an empty queue. enqueue(100): queue holds [100]. enqueue(200): queue holds [100, 200]. enqueue(300): queue holds [100, 200, 300]. dequeue(): removes oldest item 100 (not 300); queue holds [200, 300]. dequeue(): removes 200; next dequeue() removes 300, leaving the queue empty.
Edge cases include queue underflow when dequeuing an empty queue. Queues in print spoolers and web servers must handle capacity limits using bounded buffers to prevent memory exhaustion.
offer(e): inserts an item at the tail, returning false if full.poll(): removes and returns the head item, returning null if empty.peek(): inspects the head item without removing it.isEmpty(): checks whether the queue has zero elements.
- Call
offer(10)to enqueue 10 at the tail. - Call
offer(20)to enqueue 20 behind 10. - Call
peek()to view 10 at the head. - Call
poll()to remove and return 10.
Fix the error
Fix the queue method
Read the error, then pick the line that fixes it.
Round 1 of 2
Add 10 at the back of the queue.
Error
error: cannot find symbol symbol: method push(int) location: variable q of type Queue<Integer>
ArrayDeque versus LinkedList for Queue
In Java, both ArrayDeque and LinkedList implement the Queue interface. However, their performance profiles differ significantly.
ArrayDeque uses a circular array buffer. Elements sit together in memory, making CPU cache access very fast. It allocates no node wrapper objects.
Example 1 · Basic Queue Operations Using ArrayDeque
import java.util.ArrayDeque;import java.util.Queue;
public class BasicQueueDemo { public static void main(String[] args) { Queue<String> queue = new ArrayDeque<>(); queue.offer("Alice"); queue.offer("Bob"); queue.offer("Charlie");
System.out.println("Head: " + queue.peek()); System.out.println("Served: " + queue.poll()); System.out.println("Next head: " + queue.peek()); System.out.println("Size: " + queue.size()); }}Head: Alice Served: Alice Next head: Bob Size: 2
What this code does
offeradds elements to the back of the queue.pollremoves Alice first because she arrived first.peekinspects Bob without removing him.
LinkedList allocates a fresh Node object on every offer call. This creates memory overhead and increases garbage collection work. Modern Java recommends ArrayDeque for single-threaded queues.
Side by side:
ArrayDeque: cache friendly, faster, no node allocation overhead.LinkedList: allocates node objects, higher memory footprint.- Null policy:
ArrayDequeforbids null elements;LinkedListpermits them.
Queue<T> q = new ArrayDeque<>() for best single-threaded performance.Real-world uses: job queues and breadth-first search
Message brokers like RabbitMQ store tasks in queues to distribute work fairly across background worker servers.
Operating system print spoolers manage print jobs in FIFO order. The document sent first prints first.
Example 2 · Simulating a Print Spooler
import java.util.ArrayDeque;import java.util.Queue;
public class PrintSpoolerDemo { static class PrintJob { String doc; int pages; PrintJob(String doc, int pages) { this.doc = doc; this.pages = pages; } }
public static void main(String[] args) { Queue<PrintJob> spooler = new ArrayDeque<>(); spooler.offer(new PrintJob("Invoice.pdf", 2)); spooler.offer(new PrintJob("Report.docx", 10));
while (!spooler.isEmpty()) { PrintJob job = spooler.poll(); System.out.println("Printing " + job.doc + " (" + job.pages + " pages)"); } }}Printing Invoice.pdf (2 pages) Printing Report.docx (10 pages)
What this code does
- Print jobs are processed in the exact order they arrive.
poll()retrieves and removes the front job.- The while loop processes jobs until the queue is empty.
Example 3 · Generating Binary Numbers from 1 to N Using a Queue
import java.util.ArrayDeque;import java.util.Queue;
public class GenerateBinaryQueueDemo { public static void main(String[] args) { int n = 4; Queue<String> q = new ArrayDeque<>(); q.offer("1");
for (int i = 1; i <= n; i++) { String curr = q.poll(); System.out.print(curr + " "); q.offer(curr + "0"); q.offer(curr + "1"); } System.out.println(); }}1 10 11 100
What this code does
- Enqueuing
curr + 0andcurr + 1generates binary numbers in increasing order. - The FIFO queue preserves sequential level generation.
- Time complexity is O(n).
Tree and graph algorithms use queues for Breadth-First Search (BFS). Visiting nodes level by level requires queuing neighbors in order.
Where queues appear:
- Job processing: distributes tasks to worker pools in arrival order.
- Print spooler: queues document jobs fairly.
- Breadth-First Search: explores trees and graphs level by level.
Next step
Check your understanding
10 quick questions