A queue is one of the simplest data structures in Java. It works exactly like a line of people waiting for their turn; the one who comes first is served first. A Queue is a data structure that works just like a real-life queue (line) of people.
Imagine you are standing in line at a movie ticket counter. The first person in the line gets the ticket first. The new person joins from the back of the line. A queue in data structures works the same. This rule is called FIFO (First In, First Out).
Why do we use a Queue?
Any situation where things must be handled one-by-one requires a queue.
- People standing in line
- Tasks waiting to be processed
- Printers printing documents
- Call centers handling calls
- CPU scheduling (process one, then next)
What can a Queue do?
A queue mainly supports the following operations:
- enqueue(value) – add value at the back
- dequeue() – remove value from the front
- peek() – see the front value
- isEmpty() – check if the queue is empty
- isFull() – check if the queue is empty (for fixed-size queue)
Queue Implementation in Java
In this Queue in Data Structures Java code, we will create a queue using an array and learn how to add values, remove values, and check the front value. This will help you understand FIFO behavior clearly.
// Simple Java Program: Queue using Array
public class QueueUsingArray {
int[] queue;
int front;
int rear;
int size;
public QueueUsingArray(int size) {
this.size = size;
queue = new int[size];
front = 0;
rear = -1;
}
// Add value at the back
public void enqueue(int value) {
if (rear == size - 1) {
System.out.println("Queue is full");
return;
}
rear++;
queue[rear] = value;
}
// Remove value from the front
public int dequeue() {
if (front > rear) {
System.out.println("Queue is empty");
return -1;
}
int value = queue[front];
front++;
return value;
}
// Check front value
public int peek() {
if (front > rear) {
System.out.println("Queue is empty");
return -1;
}
return queue[front];
}
// Check if empty
public boolean isEmpty() {
return front > rear;
}
// Print queue
public void printQueue() {
if (isEmpty()) {
System.out.println("Queue is empty");
return;
}
System.out.print("Queue: ");
for (int i = front; i <= rear; i++) {
System.out.print(queue[i] + " ");
}
System.out.println();
}
// Testing
public static void main(String[] args) {
QueueUsingArray q = new QueueUsingArray(5);
q.enqueue(10);
q.enqueue(20);
q.enqueue(30);
q.printQueue(); // Queue: 10 20 30
System.out.println("Front: " + q.peek()); // 10
System.out.println("Dequeued: " + q.dequeue()); // 10
q.printQueue(); // Queue: 20 30
}
}