Queue Example in Java
Problem
Queue is a first-in-first-out interface — elements are added at the back with offer() and removed from the front with poll(), so whichever element has been waiting longest comes out first.
Offer a few elements to a Queue and serve them in the order they arrived.
Java Program
import java.util.ArrayDeque;
import java.util.Queue;
public class QueueExample {
public static void main(String[] args) {
Queue<String> queue = new ArrayDeque<>();
queue.offer("Alice");
queue.offer("Bob");
queue.offer("Charlie");
System.out.println("Front: " + queue.peek());
System.out.println("Served: " + queue.poll());
System.out.println("Served: " + queue.poll());
System.out.println("Front now: " + queue.peek());
}
}Output
Core Logic
Declaring the variable as a Queue, backed by ArrayDeque, and only ever adding with offer() and removing with poll() keeps the ordering strictly first-in-first-out.
- 1
Queue<String> queue = new ArrayDeque<>();declares the variable by its interface, backed by a concrete ArrayDeque. - 2
offer("Alice"),offer("Bob"),offer("Charlie")each add to the back of the queue, in that order. - 3
peek()reads the element at the front without removing it —"Alice", since it arrived first. - 4
poll()removes and returns the front element each time —"Alice", then"Bob"— leaving"Charlie"at the front.
Key Point: offer() and poll() together are what make this FIFO — offer() always adds to the back and poll() always removes from the front, so nothing can jump the line.
Why: ArrayDeque backs offer() and poll() with amortized constant-time operations on its resizable circular array, while the queue holds up to n waiting elements.