Launch your tech mastery with us—your coding journey starts now!
Course Content
Data Structure

A circular queue is the extended version of a regular queue where the last element is connected to the first element. Thus forming a circle-like structure.

The circular queue solves the major limitation of the normal queue. In a normal queue, after a bit of insertion and deletion, there will be non-usable empty space.

Circular queue representation

Circular Queue data structure illustration showing elements A, B, C, D arranged in a circle with arrows indicating enqueue at rear and dequeue at front positions.

Java Implementation

This implementation uses the modulo operator % to wrap indices around .

class CircularQueue {
    private int maxSize;
    private int[] queueArray;
    private int front;
    private int rear;
    private int currentSize;

    public CircularQueue(int size) {
        this.maxSize = size;
        this.queueArray = new int[maxSize];
        this.front = 0;
        this.rear = -1;
        this.currentSize = 0;
    }

    public void enqueue(int value) {
        if (isFull()) {
            System.out.println("Queue is full");
            return;
        }
        rear = (rear + 1) % maxSize; // Circular increment
        queueArray[rear] = value;
        currentSize++;
        System.out.println("Enqueued: " + value);
    }

    public int dequeue() {
        if (isEmpty()) {
            System.out.println("Queue is empty");
            return -1;
        }
        int value = queueArray[front];
        front = (front + 1) % maxSize; // Circular increment
        currentSize--;
        System.out.println("Dequeued: " + value);
        return value;
    }

    public boolean isEmpty() { return currentSize == 0; }
    public boolean isFull() { return currentSize == maxSize; }
}