Queue Implementation in Java Using Array
Queue Implementation in Java Using Array
html
Although Java Collections provides an in-build support to use these data structures on the fly, but as
a programmer we must know actual implementation of these things. In this particular blog we will
discuss how to implement queue in Java using Array. Queue is a commonly used and efficient data
structure with a first in first out capability. Lets see how to implement Queue push and pop
operations in java using Array.
package com.beingjavaguys.core;
/**
* @author Nagesh Chauhan
*/
public class QueueDemo {
private static final int capacity = 3;
int arr[] = new int[capacity];
int size = 0;
int top = -1;
int rear = 0;
public void push(int pushedElement) {
if (top < capacity - 1) {
top++;
arr[top] = pushedElement;
System.out.println("Element " + pushedElement
+ " is pushed to Queue !");
display();
} else {
System.out.println("Overflow !");
}
}
public void pop() {
if (top >= rear) {
rear++;
System.out.println("Pop operation done !");
display();
} else {
System.out.println("Underflow !");
}
}
public void display() {
if (top >= rear) {
System.out.println("Elements in Queue : ");
for (int i = rear; i <= top; i++) {
System.out.println(arr[i]);
}
}
}
public static void main(String[] args) {
QueueDemo queueDemo = new QueueDemo();
queueDemo.pop();
queueDemo.push(23);
queueDemo.push(2);
queueDemo.push(73);
queueDemo.push(21);
queueDemo.pop();
queueDemo.pop();
queueDemo.pop();
queueDemo.pop();
}
}
Output
If everything goes right you will see following output on console demonstrating all possible cases in
Queue Implementation.
In this particular blog we came across 'Queue Implementation in Java using Array '. In upcoming
blogs we will see more about general purpose data structures implementations in Java and other
open source Technologies.
Thanks for reading !
Being Java Guys Team