This article covers queue implementation in Java. A queue is a linear data structure that follows the FIFO (First–In, First–Out) principle. That means the object inserted first will be the first one out, followed by the object inserted next.

The queue supports the following core operations:

  1. Enqueue: Inserts an item at the rear of the queue.
  2. Dequeue: Removes the object from the front of the queue and returns it, thereby decrementing queue size by one.
  3. Peek: Returns the object at the front of the queue without removing it.
  4. IsEmpty: Tests if the queue is empty or not.
  5. Size: Returns the total number of elements present in the queue.

Practice this problem

Queue Implementation using an array:

Download  Run Code


Output:
 
Inserting 1
Inserting 2
Inserting 3
The front element is 1
Removing 1
The front element is 2
The queue size is 2
Removing 2
Removing 3
The queue is empty

 
The time complexity of enqueue(), dequeue(), peek(), isEmpty() and size() functions is constant, i.e., O(1).

Using Queue Interface:

Java’s library also contains Queue interface that specifies queue operations. Following is an example of the Queue interface using the LinkedList class:

Download  Run Code


Output:
 
The front element is A
The front element is C
The queue size is 2
The queue is not empty

 
Also See:

Circular Queue implementation in C

Queue Implementation in C++

Queue Implementation in Python

Queue Implementation using a Linked List – C, Java, and Python