How to create a queue, then enqueue and dequeue elements in Java

1 Answer

0 votes
import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
        // Create a Queue using LinkedList
        Queue<Integer> queue = new LinkedList<>();

        // Enqueue (add elements to the queue)
        System.out.println("Enqueuing elements...");
        queue.add(10);
        queue.add(20);
        queue.add(30);
        queue.add(40);
        System.out.println("Queue after enqueuing: " + queue);

        // Dequeue (remove one element)
        int removedElement = queue.poll();
        System.out.println("\nRemoved: " + removedElement);
        System.out.println("Queue now: " + queue);
        
        // Dequeue (remove all elements from the queue)
        System.out.println("\nDequeuing elements...");
        while (!queue.isEmpty()) {
            removedElement = queue.poll(); // Removes and returns the head of the queue
            System.out.println("Removed: " + removedElement);
            System.out.println("Queue now: " + queue);
        }

        // Check if the queue is empty
        if (queue.isEmpty()) {
            System.out.println("\nThe queue is now empty.");
        }
    }
}



/*
run:

Enqueuing elements...
Queue after enqueuing: [10, 20, 30, 40]

Removed: 10
Queue now: [20, 30, 40]

Dequeuing elements...
Removed: 20
Queue now: [30, 40]
Removed: 30
Queue now: [40]
Removed: 40
Queue now: []

The queue is now empty.

*/

 



answered Aug 21, 2025 by avibootz
...