Java Program for Queue Simulation
Program
import java.io.*;
import java.util.*;
class queue {
private final int size = 5;
private int front, rear;
private int que[];
queue() {
front = 0;
rear = -1;
que = new int[size];
}
void insert(int item) {
if (rear == size - 1) {
System.out.println("Queue full");
return;
} else {
que[++rear] = item;
System.out.println("Element inserted is:\t" + que[rear]);
return;
}
}
void del() {
if (front > rear) {
System.out.println("Queue Empty");
return;
} else {
System.out.println("Element deleted is:\t" + que[front]);
front++;
}
if (front > rear) {
front = 0;
rear = -1;
}
}
void display() {
if (front > rear) {
System.out.println("Queue Empty");
return;
} else {
System.out.println("Contents of Queue:");
for (int i = front; i <= rear; i++)
System.out.println(que[i]);
return;
}
}
}
public class QueueSimulation {
public static void main(String[] args) {
queue q = new queue();
int choice;
Scanner sc = new Scanner(System.in);
System.out.println("QUEUES");
while (true) {
System.out.println("1. Insert\n2. Delete\n3. Display\n4. Exit");
System.out.println("Enter choice");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Enter the item to insert");
int item = sc.nextInt();
q.insert(item);
break;
case 2:
q.del();
break;
case 3:
q.display();
break;
case 4:
sc.close();
System.exit(0);
break;
default:
System.out.println("Invalid choice");
}
}
}
}
Output
QUEUES
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
1
Enter the item to insert
10
Element inserted is: 10
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
1
Enter the item to insert
20
Element inserted is: 20
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
1
Enter the item to insert
30
Element inserted is: 30
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
1
Enter the item to insert
40
Element inserted is: 40
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
1
Enter the item to insert
50
Element inserted is: 50
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
1
Enter the item to insert
60
Queue full
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
2
Element deleted is: 10
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
2
Element deleted is: 20
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
2
Element deleted is: 30
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
3
Contents of Queue:
40
50
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
2
Element deleted is: 40
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
2
Element deleted is: 50
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
2
Queue Empty
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
3
Queue Empty
1. Insert
2. Delete
3. Display
4. Exit
Enter choice
4