How to Implement Queue in Java

Hey folks,
I am up with another tutorial. In this tutorial, we will learn how to implement a queue using Java. A queue has a concept of two pointers. One at the front element and other at last element of an array. Unlike stack which has only one pointer at the end.

So the key concept of a queue is first in first out(FIFO). It is different from the stack which follows last in first out(LIFO). FIFO means the element which is added first will be removed first.

How to implement queue in Java?

A queue has many advantages. Like it has time complexity of O(1) if we insert an element at the end. And has O(1) time complexity when an element is deleted from the front. A queue is good for storing things in an ordered form.

Basically, both stack and queue have their own advantages. The main functions which a queue perform are listed below :

• enQueue()
• deQueue()
• getSize()
• isEmpty()
• show()

We have two pointers named rear, front. Where rear represents the last element and front as the front element. We have used the enQueue function to add an element at the rear position. And we use deQueue function to delete an element from the front.

Creating Queue.java file -:

```public class Queue
{
int queue[]=new int[10];
int size;
int front;
int rear;

public void enQueue(int data)
{
queue[rear]=data;
rear=rear+1;
size=size+1;
}
public int deQueue()
{
int data=queue[front];
for(int i=0;i<rear-1;i++)
{
queue[i]=queue[i+1];
}

size=size-1;
rear--;
return data;
}
public int getsize()
{
return size;
}
public boolean isEmpty()
{
return size==0;
}

public void show()
{
System.out.print("Elements :");
for(int i=0;i<rear;i++)
{
System.out.print(queue[front +i] + " ");
}
}
}
```

In enQueue function after adding a new element, we increase the value of rear by one. And in deQueue function, we shift elements one unit backwards. But for that, we need to rewrite all the previous values. And then we decrease the value of rear by one unit. Because now our size has become one unit less.

We have created getSize() function to return the size of our queue. And isEmpty() function to check if our queue is empty or not. At last, we have created a show() function to print the elements of the queue.

Creating Runner.java file -:

```public class Runner
{
public static void main(String[] args)
{
Queue q=new Queue();
q.enQueue(2);
q.enQueue(5);
q.show();
q.deQueue();
q.enQueue(12);
q.show();
}

}
```

We have created a different file for calling the functions, so as to avoid confusion. You can also create both in a single file. In this file, we have made a new object named q of the Queue type. And then we have called all the functions one by one.

```Output
Elements :2 5
Elements :5 12```

I hope you understood the code. Feel free to ask your doubts in the comment section below.