Java Program to Implement the queue data structure

To understand this example, you should have the knowledge of the following Java programming topics:


Example 1: Java program to implement Stack

Output

Queue is empty
Insert 1
Insert 2
Insert 3
Insert 4
Insert 5
Queue is full

Front index-> 0
Items ->
1  2  3  4  5  
Rear index-> 4
1 Deleted

Front index-> 1
Items ->
2  3  4  5
Rear index-> 4

In the above example, we have implemented the queue data structure in Java.

To learn the working about the queue, visit Queue Data Structure.


Example 2: Implement stack using Queue interface

Java provides a built Queue interface that can be used to implement a queue.

Output

Queue: [1, 2, 3]
Removed Element: 1
Queue after deletion: [2, 3]

In the above example, we have used the Queue interface to implement the queue in Java. Here, we have used the LinkedList class that implements the Queue interface.

  • numbers.offer() - insert elements to the rear of the queue
  • numbers.poll() - remove an element from the front of the queue

Notice, we have used the angle brackets <Integer> while creating the queue. It represents that the queue is of the generic type.

We can also use other interfaces and classes instead of Queue and LinkedList. For example,