Skip to lesson
MentorNxt home

Java Programming

Queues, Stacks & Priority Queues

Queues: first in, first out

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.

A queue of three orders: Order 101 at the front, Order 102 in the middle and Order 103 at the back. offer(x) adds a new order at the back and poll() takes the order at the front out. First in, first out.

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.

TicketLine.javaJava
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());    }}
Output
[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

QueueBasicsDemo.javaJava
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());    }}
Output
Line: [Ravi, Sana, Tara]
Next to be served: Ravi
Served: Ravi
Served: Sana
Line now: [Tara, Uday], size 2

What this code does

  • offer adds at the tail, so the printed queue shows the head (Ravi) first. peek only looks; Ravi is still in the line after it.
  • poll removes from the head in arrival order. Uday joins behind Tara, the last person still waiting.

Example 2 · Mistake: remove() on an empty queue

EmptyRemoveDemo.javaJava
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());    }}
Sample output
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 throws NoSuchElementException. element() fails the same way.
  • Use remove() only when an empty queue would be a real bug. Otherwise use poll() or check isEmpty() first.

Example 3 · poll and peek return null instead

SafeQueueDemo.javaJava
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());    }}
Output
Peek: Kiran
Agent now chatting with Kiran
No customers waiting
Peek: null

What this code does

  • On an empty queue, poll and peek return null instead of throwing, so the method can handle "nobody waiting" with a plain if.
  • This only works because an ArrayDeque never holds null; a null result always means "empty".
  • Add at the tail: add(x) throws an exception if it fails; offer(x) returns false.
  • Take the head out: remove() throws NoSuchElementException on an empty queue; poll() returns null.
  • Look at the head without removing: element() throws NoSuchElementException; peek() returns null.
  • Everyday code uses offer, poll and peek, and checks for null.
An 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

TicketCounterDemo.javaJava
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);    }}
Output
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 with poll, 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

PrinterDemo.javaJava
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");            }        }    }}
Output
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, offer sends 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.

import java.util.*;
public class OrderLine {
public static void main(String[] args) {
Queue<String> line = new ArrayDeque<>();
line.offer("Order 101");
line.offer("Order 102");
line.offer("Order 103");
System.out.println(line.poll());
line.offer("Order 104");
System.out.println(line.poll());
System.out.println(line.peek());
System.out.println(line);
}
}

Variables

line
[]

Output

(nothing printed yet)

Line 5A new, empty queue. Nothing is waiting yet.

Step 1 of 9

Next step

Check your understanding

12 quick questions