0
0
JavaProgramBeginner · 2 min read

Java Program to Implement Queue Using Array

You can implement a queue using an array in Java by creating a class with an array and two pointers front and rear to track the start and end, and methods like enqueue() to add and dequeue() to remove elements.
📋

Examples

Inputenqueue(10), enqueue(20), dequeue(), display()
OutputDequeued element: 10 Queue elements: 20
Inputenqueue(5), enqueue(15), enqueue(25), dequeue(), dequeue(), display()
OutputDequeued element: 5 Dequeued element: 15 Queue elements: 25
Inputdequeue()
OutputQueue is empty, cannot dequeue
🧠

How to Think About It

To implement a queue using an array, think of the array as a line of boxes where you add items at the end (rear) and remove from the front. Use two pointers: one to mark where the first item is (front) and one to mark where the last item is (rear). When adding, move rear forward; when removing, move front forward. Check if the queue is full or empty before adding or removing.
📐

Algorithm

1
Initialize an array with fixed size and set front and rear to -1.
2
To enqueue, check if the queue is full; if not, move rear forward and insert the element.
3
If the queue was empty, set front to 0 when adding the first element.
4
To dequeue, check if the queue is empty; if not, remove the element at front and move front forward.
5
If after dequeue front passes rear, reset both to -1 to mark the queue empty.
6
Provide a method to display all elements from front to rear.
💻

Code

java
public class QueueUsingArray {
    private int[] queue;
    private int front, rear, size;

    public QueueUsingArray(int capacity) {
        queue = new int[capacity];
        front = -1;
        rear = -1;
        size = capacity;
    }

    public void enqueue(int element) {
        if (rear == size - 1) {
            System.out.println("Queue is full, cannot enqueue");
            return;
        }
        if (front == -1) front = 0;
        queue[++rear] = element;
        System.out.println(element + " enqueued");
    }

    public void dequeue() {
        if (front == -1 || front > rear) {
            System.out.println("Queue is empty, cannot dequeue");
            return;
        }
        System.out.println("Dequeued element: " + queue[front++]);
        if (front > rear) front = rear = -1;
    }

    public void display() {
        if (front == -1) {
            System.out.println("Queue is empty");
            return;
        }
        System.out.print("Queue elements: ");
        for (int i = front; i <= rear; i++) {
            System.out.print(queue[i] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        QueueUsingArray q = new QueueUsingArray(5);
        q.enqueue(10);
        q.enqueue(20);
        q.dequeue();
        q.display();
    }
}
Output
10 enqueued 20 enqueued Dequeued element: 10 Queue elements: 20
🔍

Dry Run

Let's trace enqueue(10), enqueue(20), dequeue(), display() through the code

1

Initialize queue

front = -1, rear = -1, size = 5, queue = [_, _, _, _, _]

2

enqueue(10)

rear moves from -1 to 0, front set to 0, queue[0] = 10

3

enqueue(20)

rear moves from 0 to 1, queue[1] = 20

4

dequeue()

front moves from 0 to 1, element 10 removed

5

display()

Print elements from front=1 to rear=1: 20

OperationfrontrearQueue State
Init-1-1[_, _, _, _, _]
enqueue(10)00[10, _, _, _, _]
enqueue(20)01[10, 20, _, _, _]
dequeue()11[10, 20, _, _, _]
display()11[10, 20, _, _, _]
💡

Why This Works

Step 1: Using front and rear pointers

The front pointer tracks where to remove elements, and rear tracks where to add new elements, simulating a line.

Step 2: Checking full and empty conditions

Before adding, we check if rear reached the array end to avoid overflow; before removing, we check if queue is empty.

Step 3: Resetting pointers when empty

When all elements are removed, resetting front and rear to -1 marks the queue as empty for future operations.

🔄

Alternative Approaches

Circular Queue using Array
java
public class CircularQueue {
    private int[] queue;
    private int front, rear, size, count;

    public CircularQueue(int capacity) {
        queue = new int[capacity];
        front = 0;
        rear = -1;
        size = capacity;
        count = 0;
    }

    public void enqueue(int element) {
        if (count == size) {
            System.out.println("Queue is full, cannot enqueue");
            return;
        }
        rear = (rear + 1) % size;
        queue[rear] = element;
        count++;
        System.out.println(element + " enqueued");
    }

    public void dequeue() {
        if (count == 0) {
            System.out.println("Queue is empty, cannot dequeue");
            return;
        }
        System.out.println("Dequeued element: " + queue[front]);
        front = (front + 1) % size;
        count--;
    }

    public void display() {
        if (count == 0) {
            System.out.println("Queue is empty");
            return;
        }
        System.out.print("Queue elements: ");
        for (int i = 0; i < count; i++) {
            System.out.print(queue[(front + i) % size] + " ");
        }
        System.out.println();
    }
}
Circular queue efficiently uses space by wrapping around, avoiding wasted slots after dequeues.
Queue using Linked List
java
class Node {
    int data;
    Node next;
    Node(int d) { data = d; next = null; }
}

public class QueueLinkedList {
    private Node front, rear;

    public void enqueue(int element) {
        Node newNode = new Node(element);
        if (rear == null) {
            front = rear = newNode;
            System.out.println(element + " enqueued");
            return;
        }
        rear.next = newNode;
        rear = newNode;
        System.out.println(element + " enqueued");
    }

    public void dequeue() {
        if (front == null) {
            System.out.println("Queue is empty, cannot dequeue");
            return;
        }
        System.out.println("Dequeued element: " + front.data);
        front = front.next;
        if (front == null) rear = null;
    }

    public void display() {
        if (front == null) {
            System.out.println("Queue is empty");
            return;
        }
        System.out.print("Queue elements: ");
        Node temp = front;
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
        System.out.println();
    }
}
Linked list queue dynamically grows without fixed size but uses extra memory for pointers.

Complexity: O(1) time, O(n) space

Time Complexity

Both enqueue and dequeue operations take constant time O(1) because they only move pointers and assign values without loops.

Space Complexity

The queue uses an array of fixed size n, so space complexity is O(n). No extra space is used besides the array and pointers.

Which Approach is Fastest?

Array-based queue is fast and simple but can waste space; circular queue improves space use; linked list queue uses dynamic memory but has pointer overhead.

ApproachTimeSpaceBest For
Simple Array QueueO(1)O(n)Small fixed-size queues
Circular QueueO(1)O(n)Efficient space use with fixed size
Linked List QueueO(1)O(n)Dynamic size queues without fixed limit
💡
Always check if the queue is full before enqueue and empty before dequeue to avoid errors.
⚠️
Beginners often forget to reset front and rear pointers when the queue becomes empty after dequeues.