Queues: first in, first out
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A queue is a collection where the first value added is the first one taken out: first in, first out, or FIFO. It works exactly like the line at a railway ticket counter.
First in, first out
A queue is a collection where new values join at the back and values leave from the front, so the first value added is the first one removed. This rule is called first in, first out (FIFO).
A queue follows one rule: first in, first out. At a ticket counter, new people join at the back, and the clerk serves the person at the front. Nobody jumps the line. A queue in code works the same way.
The front of the queue is called the head; the back is the tail. Adding at the tail is called enqueue, and taking from the head is dequeue.
Queues appear wherever work must be done in arrival order: print jobs, customer-care chats, orders in an online store, and messages waiting to be sent.
Queue in Java
ArrayDeque is the Java class, in java.util, that stores a queue, a stack or a deque in a resizable array. It is fast and light, so it is the usual choice for a Queue.
Queue is an interface in java.util. Create the real queue with ArrayDeque: Queue<String> line = new ArrayDeque<>();. The code below adds three customers, prints the queue, then walks it with for-each.
import java.util.*;
public class TicketLine { public static void main(String[] args) { Queue<String> line = new ArrayDeque<>(); line.add("Asha"); line.add("Ravi"); line.add("Meena"); System.out.println(line); for (String name : line) { System.out.println("Waiting: " + name); } System.out.println(line.size()); }}[Asha, Ravi, Meena] Waiting: Asha Waiting: Ravi Waiting: Meena 3
ArrayDeque keeps its values in an array that grows when needed. (The name means "array double-ended queue"; the Deque lesson explains the double-ended part.) LinkedList also implements Queue. It works, but each value needs an extra node object, so it uses more memory. Prefer ArrayDeque.
A queue has no index: no get(2). You can still call size() and isEmpty(), print it (head first), or walk it with for-each from head to tail. Looking with for-each does not remove anything.
Two sets of methods
offer adds a value at the back of a queue, poll removes and returns the front value, and peek returns the front value without removing it. On an empty queue poll and peek return null instead of throwing an exception.
For each job, Queue has two methods. They do the same work and differ only in what happens when they cannot do it.
Example 1 · offer, peek and poll
import java.util.ArrayDeque;import java.util.Queue;
public class QueueBasicsDemo { public static void main(String[] args) { Queue<String> line = new ArrayDeque<>(); line.offer("Ravi"); line.offer("Sana"); line.offer("Tara"); System.out.println("Line: " + line); System.out.println("Next to be served: " + line.peek());
System.out.println("Served: " + line.poll()); System.out.println("Served: " + line.poll()); line.offer("Uday"); System.out.println("Line now: " + line + ", size " + line.size()); }}Line: [Ravi, Sana, Tara] Next to be served: Ravi Served: Ravi Served: Sana Line now: [Tara, Uday], size 2
What this code does
offeradds at the tail, so the printed queue shows the head (Ravi) first.peekonly looks; Ravi is still in the line after it.pollremoves from the head in arrival order. Uday joins behind Tara, the last person still waiting.
Example 2 · Mistake: remove() on an empty queue
import java.util.ArrayDeque;import java.util.Queue;
public class EmptyRemoveDemo { public static void main(String[] args) { Queue<String> orders = new ArrayDeque<>(); orders.offer("Laptop"); System.out.println("Packing " + orders.remove()); System.out.println("Packing " + orders.remove()); }}Packing Laptop Exception in thread "main" java.util.NoSuchElementException at java.base/java.util.ArrayDeque.removeFirst(ArrayDeque.java:362) at java.base/java.util.ArrayDeque.remove(ArrayDeque.java:523) at EmptyRemoveDemo.main(EmptyRemoveDemo.java:9)
What this code does
- The first
remove()takes the only order. The second finds the queue empty and throwsNoSuchElementException.element()fails the same way. - Use
remove()only when an empty queue would be a real bug. Otherwise usepoll()or checkisEmpty()first.
Example 3 · poll and peek return null instead
import java.util.ArrayDeque;import java.util.Queue;
public class SafeQueueDemo { static void serveNext(Queue<String> chats) { String next = chats.poll(); if (next == null) { System.out.println("No customers waiting"); } else { System.out.println("Agent now chatting with " + next); } }
public static void main(String[] args) { Queue<String> chats = new ArrayDeque<>(); chats.offer("Kiran"); System.out.println("Peek: " + chats.peek());
serveNext(chats); serveNext(chats); System.out.println("Peek: " + chats.peek()); }}Peek: Kiran Agent now chatting with Kiran No customers waiting Peek: null
What this code does
- On an empty queue,
pollandpeekreturnnullinstead of throwing, so the method can handle "nobody waiting" with a plainif. - This only works because an
ArrayDequenever holdsnull; anullresult always means "empty".
- Add at the tail:
add(x)throws an exception if it fails;offer(x)returnsfalse. - Take the head out:
remove()throwsNoSuchElementExceptionon an empty queue;poll()returnsnull. - Look at the head without removing:
element()throwsNoSuchElementException;peek()returnsnull. - Everyday code uses
offer,pollandpeek, and checks fornull.
ArrayDeque grows as needed, so add and offer both succeed on it. Some queues have a size limit; there offer returns false when the queue is full.Processing a queue
The usual way to process a queue is a while loop that polls until the queue is empty. The examples below serve a line of ticket buyers and then share one printer between several jobs.
Example 4 · A railway ticket counter
import java.util.ArrayDeque;import java.util.Queue;
record Passenger(String name, String to, int tickets) {}
public class TicketCounterDemo { static int fare(String to) { return switch (to) { case "Pune" -> 150; case "Nashik" -> 210; default -> 300; }; }
public static void main(String[] args) { Queue<Passenger> counter = new ArrayDeque<>(); counter.offer(new Passenger("Anil", "Pune", 2)); counter.offer(new Passenger("Bina", "Nashik", 1)); counter.offer(new Passenger("Chetan", "Surat", 3));
int collected = 0; int token = 1; while (!counter.isEmpty()) { Passenger p = counter.poll(); int amount = fare(p.to()) * p.tickets(); collected = collected + amount; System.out.println("Token " + token + ": " + p.name() + ", " + p.tickets() + " x " + p.to() + " = Rs. " + amount); token++; } System.out.println("Counter closed. Collected Rs. " + collected); }}Token 1: Anil, 2 x Pune = Rs. 300 Token 2: Bina, 1 x Nashik = Rs. 210 Token 3: Chetan, 3 x Surat = Rs. 900 Counter closed. Collected Rs. 1410
What this code does
- The
while (!counter.isEmpty())loop is the standard way to process a queue: take the head withpoll, handle it, repeat. - Passengers are served in the exact order they joined. At the end the queue is empty.
Example 5 · Round robin: a shared printer
import java.util.ArrayDeque;import java.util.Queue;
class PrintJob { final String owner; int pagesLeft;
PrintJob(String owner, int pages) { this.owner = owner; this.pagesLeft = pages; }}
public class PrinterDemo { public static void main(String[] args) { Queue<PrintJob> jobs = new ArrayDeque<>(); jobs.offer(new PrintJob("Asha", 5)); jobs.offer(new PrintJob("Bilal", 1)); jobs.offer(new PrintJob("Chitra", 3));
int turn = 2; while (!jobs.isEmpty()) { PrintJob job = jobs.poll(); int printed = Math.min(turn, job.pagesLeft); job.pagesLeft = job.pagesLeft - printed; System.out.print(job.owner + ": printed " + printed); if (job.pagesLeft > 0) { jobs.offer(job); System.out.println(", " + job.pagesLeft + " left, back in line"); } else { System.out.println(", done"); } } }}Asha: printed 2, 3 left, back in line Bilal: printed 1, done Chitra: printed 2, 1 left, back in line Asha: printed 2, 1 left, back in line Chitra: printed 1, done Asha: printed 1, done
What this code does
- Each job prints at most 2 pages per turn. If pages remain,
offersends it to the tail, behind everyone who was waiting. - Bilal's one-page job finishes on the first round instead of waiting for all 5 of Asha's pages. That fairness is the point of round robin.
The usual loop is while (!queue.isEmpty()) { Task t = queue.poll(); ... }. Each pass takes the head and works on it, until nothing is left. Because poll uses null to mean "empty", ArrayDeque does not allow you to store null: offer(null) throws NullPointerException. This is a good thing: a null from poll can only mean the queue is empty.
A job that is not finished can go to the back again with offer. This is called round robin: everyone gets a short turn, in order, again and again, so no single big job blocks the rest.
Trace the code
Watch the line change
Step through offer, poll and peek and watch the queue after each line.
Variables
- line
- []
Output
(nothing printed yet)Line 5A new, empty queue. Nothing is waiting yet.
Next step
Check your understanding
12 quick questions