×

Implementing Queue Using Array in Java

We can implement queue by using array in Java. The queue is a linear data structure, and the array is one of the simplest data structures. Before implementing a queue using an array, let us know about the queue and its operations, and we also will learn about arrays.

Queue Data Structure

The queue data structure is open at both ends. If we compare the queue with the stack data structure, the stack is opened only at one end. It is one of the linear data structures. This queue is called a linear data structure because the arrangements of the elements or the data we are given follow a linear trend. In the queue data structure, the data is arranged in such a way that the data or element is directly linked to the previous data or element and also the next data or element. It follows First In First Out (FIFO). First in, first out means if the element is added first in the queue, then the same will be get deleted or else, we can it will be removed from the queue.

Not only in the java programming language but also, we can implement queues using arrays in other programming languages also, like C++, Python, C#, Java, in Javascript. We know that the array will have a fixed size, so we can only pass a fixed number of elements into the array. So, because the array is fixed size, an issue will occur in the implementation of the queue when we want to implement a queue using an array. A gap will be created in the queue data structure when an element is added to the queue and deleted from the queue. But we can fill this gap by rearing the elements which are remained, but this process of rearranging is a time-consuming process. So, to overcome this issue, we can use a circular queue which is one of the types of queue data structure. By using this circular queue while implementing the queue using an array, even after reaching the maximum size of the array, we can proceed.

Array

We can define the array as the simplest data structure when compared to others. In this array, we can store data elements which are similar at contiguous locations. The elements which are of the same type only like if we declared the array as int we could not pass characters into the array along with the integers.

Steps for Implementing the Queue Using Array

  • First, create an array of some size.
  • Take two variables where each variable should represent the "front" of the queue and the "rear" of the queue.
  • Initialize those two variables to "zero". The reason is queue is empty at the start, so we do not have any elements in the queue. So, that is the reason we initialize those two variables to zero at the start.
  • The rear is the index which indicates whether the elements are stored in the array or not. And the front is the index in the queue, which indicates the first element of the array.

These are the few steps that need to be followed when we are implementing the queue using array not only in a java programming language but also in other programming languages too.

Insertion of the element into the queue, deletion of the element from the queue, display and front are the operations that we can do on a queue-based system.

At the rear end, the insertion of the element is done. So, whenever we want to add an element to the queue, we have to add that particular element to the rear side. This adding of element into the queue is also known as "Enqueue".

At the front end, the deletion of the element is done. So, whenever we want to delete an element from the queue, we have to delete that element from the front end. This is deleting an element from the queue, also known as "Dequeue".

And display operation will display all the elements of the queue.

By the front operation in the queues, we can get the front element from the queue.

ImplementingQueue.java

Public class ImplementingQueue 
{  
  private int maxSize;  
  private int[] queueArray;  
  private int front;  
  private int rear;  
  private int currentCapacity;  
  public ImplementingQueue (int size)  
  {  
    this.maxSize = size;  
    this.queueArray = new int[size];  
    front = 0;  
    rear = -1;  
    currentCapacity = 0;  
  }  
  public void insert(int item)  
  {  
    if(isQueueFull())  
    {  
      System.out.println("Queue data structure is full");  
      return;  
    }  
    if(rear == maxSize - 1)  
{  
      rear = -1;  
    }  
    //Incrementing the rear
    queueArray[++rear] = item;  
    currentCapacity++;  
    System.out.println("Enqueue is done: " + item);  
  }  
  //Dequeue operation
  public int delete()  
  {  
    if(isQueueEmpty())  
    {  
      throw new RuntimeException("Queue is empty");  
    }  
    int temp = queueArray[front++];  
    if(front == maxSize)  
    {  
      front = 0;  
    }  
    currentCapacity--;  
    return temp;
}  
 //peek operation      
  public int peek()  
  {  
    return queueArray[front];  
  }  
  public boolean isQueueFull()  
  {  
    return (maxSize == currentCapacity);  
  }      
  public boolean isQueueEmpty()  
{  
    return (currentCapacity == 0);  
  }  
  public static void main(String[] args)   
  {  
    ImplementingQueue  queue = new ImplementingQueue (10);  
    queue.insert(8);  
    queue.insert(9);  
    System.out.println("Deleted item form the queue: " + queue.delete());  
    System.out.println("Deleted item from the queue: " + queue.delete());  
    queue.insert(10);      
    System.out.println("Deleted item from the queue: " + queue.delete());      
  }  
}  

Output:

Implementing Queue Using Array in Java Programming Language

Related Topics

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Java.net.SocketException

Exception The problem occurred during the execution of the program. If an exception occurs in the program, the program gets terminated. To skip the exception occurring statements, we have to handle...

4 minutes read.

Lombok Java

What is Lombok java? A well-liked and widely-used Java framework that is used to reduce or eliminate boilerplate code is called Project Lombok. Both time and effort are saved. We may...

7 minutes read.

Interface in Java

  Interface in Java In Java, the interface is just like a class that has only static constants and abstract methods. It is used to achieve polymorphism so that it can also...

6 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

How to check Date is Greater in Java?

In this article, you will be acknowledged about how to check if the given date is greater than the other date or not. We are simply comparing the dates and...

7 minutes read.

Coin change problem in dynamic programming

In this tutorial, we will understand a popular problem called the coin changeproblem through dynamic programming. This problem checks the logical and critical thinking ability of the person. Dynamic Programming...

5 minutes read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

Java Exception Propagation

Java Exception Propagation When an exception is being thrown from the peak of the stack and not getting caught, it runs down the stack to the previous method, which is sitting...

3 minutes read.

Java DatagramSocket and Java DatagramPacket

Datagrams TCP/IP style networking specifies a serialized, predictable, and reliable stream of data in the form of a packet. Servers and clients communicate through a reliable channel, such as TCP socket, have a dedicated...

6 minutes read.

Cyclic Barrier in Java

Programmers often find it challenging to run multiple threads simultaneously. Java introduces the idea of concurrency, which enables us to run many threads concurrently, making this work simpler. Concurrent programming...

6 minutes read.

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

&& Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.