×

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

How to take Multiple String Input in Java using Scanner class

Scanner class is a class which takes the multiple input data or the single input data through an objects and methods. The Scanner class will be available in the java.util...

3 minutes read.

How to reverse a linked list in java

The process of reversing a linked list in Java will be covered in this section. One of the most common questions in interviews is about reversing a linked list. If...

11 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Java String Interview Questions

Java String Interview Questions String is the most common and important discussed topics in a Java interview. In Java interview interviewer generally asked three to four questions based on String concept....

16 minutes read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Java String toUpperCase() methods

Java String toUpperCase() method is used to convert all the characters of the String into upper case. Syntax public String toUpperCase() public String toUpperCase(Locale locale) Returns It returns upper case String. Java String toUpperCase() Example 1: public...

1 minute read.

Pyramid Program in Java

Pyramid Program in Java In the previous section, we have discussed about the number pattern programs in Java. The logic for the number pattern and pyramid pattern is the same except...

2 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Why main method is static in Java

The method serves as the entry point for Java programmes or simply the point from which the programme begins to run. As a result, it is one of the most...

4 minutes read.

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

History and Evolution of Java

Java is invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. Java is related to C++, which is inherited from...

3 minutes read.

User Defined Exception in Java

An exception is an error (run time error) that happened while a program was being executed. The program stops abruptly whenever the Exception occurs, and the code after the line...

3 minutes read.

Ad Hoc Problem on Arrays in Java

Ad hoc problems are issues that arise unexpectedly and require immediate attention. These problems can range from small and straightforward issues to more complex and time-consuming problems. Examples of ad...

3 minutes read.

Java time local date

Java: Java is one of the programming language which is object oriented. It consists of many features such as robust, simple, architecture neutral, dynamic, distributed, multi threaded, portable etc. The main feature...

3 minutes read.

Java Float Keyword

Float: In general, there are two categories of data types: primitive data types and non-primitive data types. So, float is the data type which is a primitive data type. Declarating the variables and...

3 minutes read.

Session Tracking in Java

When a series of requests from the same User (i.e., requests coming from the same browser) occurs over an extended period of time, servlets employ a mechanism known as session...

3 minutes read.