VOOZH about

URL: https://www.geeksforgeeks.org/java/implement-a-circular-queue-in-java/

⇱ How to Implement a Circular Queue in Java ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Implement a Circular Queue in Java ?

Last Updated : 23 Jul, 2025

A Circular Queue is a queue in which we can insert an element at the start of the Array even if our rare is reached at the last index and if we have space at the start of the array. This reduces the problem of inefficient use of array space. Once the array is filled till the last and if we have space at the beginning of an array, we fill the element at the front we perform insertion in a circular manner that's why it is known as a circular queue.

Approach to Implementing a Circular Queue

If we observe there is a problem in the above method.

  • While inserting the element in a queue instead of incrementing the index by one what we will do here is we will increase the index as (index+1) % size.
  • Because of this increment when we reach the end of the queue and do increment, we will again reach index 0.
  • If that index is empty which can be because of the removal of an element we can reutilize that space to insert new elements.
  • In this method, when we go to the end index, we again come to the front of the queue which is why it is known as a circular queue.

Program to Implement a Circular Queue in Java

Below is the Program to implement a Circular Queue in Java:


Output
Peek: 1
Dequeue: 1
Peek after dequeue: 2


Explanation of code:

  • In this code, while inserting instead of inserting element in next space we are incrementing it by one and then performing modulo operation with it.
  • So that it can go to the first element after last element.
  • It results in implementation of circular data structures which uses the memory more efficiently.

Complexity of the above Program:

Time Complexity:

  • Enqueue operation: O(1)
  • Dequeue operation: O(1)
  • Peek operation: O(1)
  • isEmpty operation: O(1)

Space Complexity: O(N) where N is the size of the circular queue.

Comment