Java ProgramsCollectionsQueue Example

Queue Example in Java

beginner·  Collections  ·  Queue & Stack

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.

Input
offer("Alice"), offer("Bob"), offer("Charlie")
Output
Front: Alice Served: Alice Served: Bob Front now: Charlie

Java Program

Java
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

Front: Alice Served: Alice Served: Bob Front now: Charlie

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.

How It Works
  1. 1Queue<String> queue = new ArrayDeque<>(); declares the variable by its interface, backed by a concrete ArrayDeque.
  2. 2offer("Alice"), offer("Bob"), offer("Charlie") each add to the back of the queue, in that order.
  3. 3peek() reads the element at the front without removing it — "Alice", since it arrived first.
  4. 4poll() removes and returns the front element each time — "Alice", then "Bob" — leaving "Charlie" at the front.
Alice arrives first and is served first; after two poll() calls, Charlie — the last one offered — is the only one left.
💡

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.

Complexity
Time Complexity: O(1)Space Complexity: O(n)

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.

Key Concepts

Queue interfaceoffer()poll()FIFO order

Related Programs