WikiGalaxy

Personalize

Queues in Java

Introduction to Queues:

A queue is a linear data structure that follows the First In First Out (FIFO) principle. It is used to store data in an ordered manner where elements are added from one end (rear) and removed from the other (front).

Common Queue Operations:

The main operations in a queue are enqueue (adding an element), dequeue (removing an element), front (accessing the first element), and isEmpty (checking if the queue is empty).

Applications of Queues:

Queues are widely used in scenarios like managing requests in web servers, handling tasks in operating systems, and in breadth-first search algorithms.

    Step 1: Initialize an empty queue.
    Step 2: Enqueue elements into the queue.
    Step 3: Dequeue elements from the queue.
    Step 4: Access the front element.
    Step 5: Check if the queue is empty.
  

import java.util.LinkedList;
import java.util.Queue;

public class QueueExample {
    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();
        
        // Enqueue elements
        queue.add("Element 1");
        queue.add("Element 2");
        queue.add("Element 3");
        
        // Display the queue
        System.out.println("Queue: " + queue);
        
        // Dequeue an element
        String removedElement = queue.poll();
        System.out.println("Removed Element: " + removedElement);
        
        // Display the queue after dequeue
        System.out.println("Queue after dequeue: " + queue);
        
        // Access the front element
        String frontElement = queue.peek();
        System.out.println("Front Element: " + frontElement);
        
        // Check if the queue is empty
        boolean isEmpty = queue.isEmpty();
        System.out.println("Is the queue empty? " + isEmpty);
    }
}
    

Explanation:

The above code demonstrates the basic operations of a queue using Java's LinkedList class which implements the Queue interface. Elements are added using add(), removed using poll(), and accessed using peek().

Console Output:

Queue: [Element 1, Element 2, Element 3]

Removed Element: Element 1

Queue after dequeue: [Element 2, Element 3]

Front Element: Element 2

Is the queue empty? false

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025