View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Queue in Java: Implementation, Methods, and Examples

Updated on 28/04/20253,976 Views

In Java programming, a Queue is a vital data structure that stores elements in a sequential manner, following the First-In, First-Out (FIFO) principle. It ensures that the element added first is the one removed first, making it ideal for managing real-world processes like task scheduling, printer queues, and order processing systems. Java programming provides the Queue interface under the java.util package, along with multiple implementations. In this guide, we’ll explore how the Queue in Java works, its basic operations, and its implementation in Java.

Build a strong career in Java programming — check out upGrad’s Software Engineering program today!

Queue Data Structure

A Queue is a linear data structure that follows the First-In, First-Out (FIFO) principle. This means the element that is inserted first is the one that gets removed first. Think of a queue like a line at a ticket counter — the person who arrives first is served first.

In Java, the Queue is an interface provided in the java.util package. Classes like LinkedList, PriorityQueue, and ArrayDeque implement this interface to provide various types of queue behaviors.

Shape a successful career in AI and data science with these top academic programs:

Basic Operations of Queue 

Several key operations are performed to manage data inside a queue. Understanding these basic operations of a queue is essential before diving into implementation.

Enqueue (Insertion)

Enqueue adds an element to the rear (end) of the queue. In Java, this is done using the add() or offer() methods.

Dequeue (Removal)

Dequeue removes an element from the front of the queue. In Java, you can perform this using the remove() or poll() methods.

IsEmpty (Check if Queue is Empty)

IsEmpty checks whether the queue has any elements or not. In Java, calling isEmpty() returns true if the queue is empty.

IsFull (Check if Queue is Full)

IsFull is more relevant for fixed-size queues (like arrays). It checks if the queue cannot accept more elements. In dynamic structures like LinkedList, this isn’t a concern.

Peek (View Front Element)

Peek retrieves the element at the front of the queue without removing it. You can use the peek() or element() method in Java.

Must read: Difference Between Linear and Non-Linear Data Structures

Working of Queue in Java

Here’s how the working of a queue looks step-by-step:

  1. Enqueue: New elements are inserted at the rear end.
  2. Dequeue: Elements are removed from the front.
  3. The queue maintains a logical order of processing based on arrival time.
  4. Internal pointers or indices track the front and rear positions in static queues.
  5. In dynamic queues (like LinkedList), nodes dynamically point to the next element.

This ensures that the first element inserted is always the first to come out, preserving FIFO behavior.

Also check: Stack and Queue in Java

Implementation of Queue in Java

Let's see how you can perform a basic Queue implementation in Java using the LinkedList class.

Example: Queue Implementation Using LinkedList

Scenario:

Suppose you are managing a print job queue, where the first document sent to the printer must be printed first.

Java Code:

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

public class PrintJobQueue {
    public static void main(String[] args) {
        Queue<String> printQueue = new LinkedList<>();

        // Enqueue elements
        printQueue.add("Document1");
        printQueue.add("Document2");
        printQueue.add("Document3");

        System.out.println("Print Queue: " + printQueue);

        // Peek at the front document
        System.out.println("First document to print: " + printQueue.peek());

        // Dequeue elements
        printQueue.remove();
        System.out.println("Queue after printing one document: " + printQueue);

        // Check if the queue is empty
        System.out.println("Is print queue empty? " + printQueue.isEmpty());
    }
}

Explanation:

  • add() inserts documents into the queue.
  • peek() shows the document at the front.
  • remove() processes (prints) the document and removes it from the queue.
  • isEmpty() checks if there are any documents left.

Check out: Difference between LinkedList and Array in Java

Implementation of Each Queue Method in Java

1. add() – Insert element into Queue

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

public class Main {
    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();
        queue.add("Apple");
        System.out.println(queue);
    }
}

Output:

[Apple]

Explanation: The add() method inserts an element at the rear of the queue. It throws an exception if the queue is capacity-restricted and full (not an issue with LinkedList).

Must explore: Types of Linked List in Java

2. offer() – Insert element safely

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

public class Main {
    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();
        queue.offer("Banana");
        System.out.println(queue);
    }
}

Output:

[Banana]

Explanation:

The offer() method also adds an element to the rear but returns false if insertion fails instead of throwing an exception, making it safer for limited-capacity queues.

Also read: Doubly Linked List Data Structures: A Complete Guide

3. remove() – Remove and return front element

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

public class Main {
    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();
        queue.add("Cat");
        System.out.println(queue.remove());
    }
}

Output

Cat

Explanation:

The remove() method deletes and returns the front element. If the queue is empty, it throws a NoSuchElementException.

Must explore: Recursion in Data Structures: Types, Algorithms, and Applications

4. poll() – Remove front element safely

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

public class Main {
    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();
        queue.add("Dog");
        System.out.println(queue.poll());
    }
}

Output:

Dog

Explanation:

The poll() method also removes the front element but returns null instead of throwing an exception if the queue is empty.

Also explore: Stack and Heap Memory in Java: Key Differences Explained

5. peek() – View front element without removing

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

public class Main {
    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();
        queue.add("Elephant");
        System.out.println(queue.peek());
    }
}

Output:

Elephant

Explanation:

The peek() method retrieves but does not remove the head of the queue. If the queue is empty, it returns null.

6. element() – View front element strictly

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

public class Main {
    public static void main(String[] args) {
        Queue<String> queue = new LinkedList<>();
        queue.add("Fish");
        System.out.println(queue.element());
    }
}

Output:

Fish

Explanation:

The element() method also retrieves the front without removal, but throws a NoSuchElementException if the queue is empty instead of returning null.

Conclusion

Queue in Java is a fundamental concept every developer should master. It ensures first-come, first-served data management, which is critical in many real-world scenarios like scheduling, task management, and system resource handling. By understanding basic queue operations, the working of a queue, and Java queue implementation, you can design more efficient and scalable applications.

FAQs

1. How does Queue work internally in Java?

Queue in Java follows the First-In, First-Out (FIFO) principle. Elements are inserted at the rear and removed from the front. Java provides the Queue interface and classes like LinkedList and PriorityQueue to efficiently manage the ordering and processing of elements internally.

2. What are the different types of Queues in Java?

Java supports several types of queues: Simple Queue, Circular Queue, Priority Queue, and Deque (Double-Ended Queue). Each type modifies how elements are inserted, removed, or prioritized, depending on specific requirements like order maintenance or priority-based processing.

3. Why is LinkedList used for implementing Queue?

LinkedList is often used because it allows constant time insertion and removal from both ends. It implements the Queue interface directly and does not require resizing like arrays, making it perfect for dynamic memory and real-time queue operations.

4. What is the difference between add() and offer() methods in Queue?

Both add() and offer() insert elements into the queue. The difference is:

  • add() throws an exception if insertion fails.
  • offer() returns false instead of throwing an exception. Thus, offer() is safer when using capacity-restricted queues.

5. What is the difference between remove() and poll() methods in Queue?

Both remove() and poll() remove and return the head element.

  • remove() throws a NoSuchElementException if the queue is empty.
  • poll() returns null instead of throwing an exception, making it safer for empty queues.

6. What is the role of peek() method in Queue?

The peek() method retrieves, but does not remove, the head of the queue. If the queue is empty, it returns null. It’s helpful when you want to check the next element to process without actually removing it.

7. Can we use PriorityQueue as a normal Queue in Java?

Yes, but PriorityQueue does not maintain FIFO order. It orders elements based on their natural ordering or a provided comparator. It is used when processing order depends on priority rather than the sequence of insertion.

8. Is Queue thread-safe in Java?

No, standard queues like LinkedList and PriorityQueue are not thread-safe. For thread-safe operations, you should use ConcurrentLinkedQueue, BlockingQueue, or wrap the queue with Collections.synchronizedQueue() for synchronization.

9. Can a Queue in Java store null elements?

Some queue implementations like LinkedList allow null elements, but others like PriorityQueue do not allow null values. Using nulls can cause NullPointerException in queues that rely on comparison or ordering of elements.

10. What is BlockingQueue in Java?

BlockingQueue is a special type of queue that blocks the operation:

  • When trying to remove an element from an empty queue, or
  • Insert into a full queue (in bounded queues). It is heavily used in multithreading and producer-consumer scenarios.

11. How is a Deque different from a normal Queue in Java?

A Deque (Double-Ended Queue) allows insertion and removal of elements from both ends — front and rear. A normal Queue allows insertion at the rear and removal only from the front, following strict FIFO behavior.

image

Take the Free Quiz on Java

Answer quick questions and assess your Java knowledge

right-top-arrow
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

Free Courses

Explore Our Free Software Tutorials

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918068792934

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.