This program demonstrates how to implement a basic queue using an array. A queue is a First In First Out (FIFO) data structure where elements are added to the rear and removed from the front.
Program Structure
- Queue Class: Contains methods for enqueue (add), dequeue (remove), and display operations, along with a constructor to initialize the queue.
- Main Method: Demonstrates the functionality of the queue with enqueue and dequeue operations.
Java Code
public class ArrayQueue {
private int[] queue;
private int front, rear, capacity;
public ArrayQueue(int size) {
capacity = size;
queue = new int[capacity];
front = 0;
rear = -1;
}
public void enqueue(int data) {
if (rear == capacity - 1) {
System.out.println("Queue is full");
} else {
queue[++rear] = data;
}
}
public int dequeue() {
if (front > rear) {
System.out.println("Queue is empty");
return -1;
} else {
return queue[front++];
}
}
public void displayQueue() {
if (front > rear) {
System.out.println("Queue is empty");
} else {
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) {
ArrayQueue q = new ArrayQueue(5);
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.displayQueue();
q.dequeue();
q.displayQueue();
}
}
Explanation of How the Program Works
- Queue Initialization: The constructor initializes the queue with a given capacity, setting front to 0 and rear to -1.
- Enqueue Operation: Adds an element to the rear of the queue if it is not full.
- Dequeue Operation: Removes and returns the front element of the queue if it is not empty.
- Display Method: Prints all elements from front to rear.
Key Components:
- ArrayQueue Class: This class manages the queue operations. It uses an array to store the queue elements and two pointers (
frontandrear) to track the ends of the queue. - Constructor: Sets up the array and initializes
frontandrear. - Enqueue Method: Adds an element to the end of the queue.
- Dequeue Method: Removes an element from the front of the queue.
- DisplayQueue Method: Outputs all elements in the queue.
This structure is ideal for educational purposes or simple applications where the queue size is known in advance and does not need to dynamically resize.
Conclusion
This array-based implementation of a queue is straightforward and effective for demonstrating basic queue operations. It handles the fundamental operations of enqueue and dequeue efficiently in constant time O(1), making it suitable for scenarios where quick and predictable performance is necessary.

