In this Data structures tutorial we will learn what is Queues in java with example and program. We will learn how to implement your own Queues in java. We will learn how to insert and remove element from Queues in java.

if (rear == size ) // means we are at last position (deal with wrapAround)

rear = 0;

queueAr[rear++] = value; // Insert element and increment rear

number++; //increase number of elements in Queue

}

/**

* Removes elements from front of Queue

*/

publicint remove(){

if(isEmpty()){

thrownew QueueEmptyException("Queue is empty");

}

int deletedValue = queueAr[front++]; // get value at front and than increment front

if (front == size) // deal with wrapAround

front = 0;

number--; //reduce number of elements in Queue

return deletedValue;

}

/**

* @return true if Queue is empty

*/

publicboolean isEmpty() {

return (number == 0);

}

/**

* @return true if Queue is full

*/

publicboolean isFull() {

return (number == size);

}

}

/**

* QueueExample - Main class

*/

publicclass QueueExample {

publicstaticvoid main(String[] args) {

Queue queue = new Queue(10); // queue holds 10 elements

queue.insert(31);

queue.insert(49);

queue.remove();

queue.remove();

queue.insert(90);

queue.insert(81);

queue.insert(72);

queue.insert(22); // At this point we got to deal with wrapAround, because rear must be pointing to last position.

System.out.print("Deleted elements from queue: ");

System.out.print(queue.remove()+ " ");

System.out.print(queue.remove()+ " ");

System.out.print(queue.remove()+ " ");

System.out.print(queue.remove()+ " ");

}

}

/** OUTPUT

Deleted elements from queue: 90 81 72 22

*/

If we analyze output queue example, we will find that- first element added to the queue was the first one to be removed in java.

Complexity of Queues in java>

Insert - O(1) [as we insert element at Rear of queue] in java

Remove - O(1) [as we remove element from front of queue] in java

So in this Data structures tutorial we learned what is Queues in java with example and program. We will learn how to implement your own Queues in java. We learned how to insert and remove element from Queues in java.

Having any doubt? or you you liked the tutorial! Please comment in below section.