×

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

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

Object Oriented Programming (OOPs)

Since the dawn of earth, we have kept on evolving. The need for evaluation comes with the aim of improving the existing systems when something inappropriate is found for the...

5 minutes read.

Java program to print matrix in Z form

In this article, you will be acknowledged about what is a matrix along with an example. Also, most importantly, you will learn how to print matrix in Z form. What is...

5 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

Stone Game in Java

In this tutorial, we will learn to design a stone game in Java. First of all, we will understand what is this game all about. We will grasp it through...

9 minutes read.

Java Math abs() Method

The abs() method of Math class returns the absolute value of the argument where the argument can be int, double, float, long. Syntax public static int abs(int a) public static float abs(float a) public...

2 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

ArrayList VS Linked List

ArrayList VS Linked List Both the ArrayList and LinkedList implements the List interface, and they have some differences as well as some similarities between them. The internal working and performance of both vary significantly. Let’s...

7 minutes read.

Java Math expm1() Method

The expm1() method of Math class returns ex-1 where e represents Euler’s number. Syntax: public static double expm1(double x) Parameters: The parameter ‘x’ represents the exponent to raise e in the calculation of ex-1. Return...

2 minutes read.

Java Custom Exception

Java Custom Exception Java language facilitates us to create our own exceptions. The class intended to throw the Custom Exception has to be derived from the Java Exceptionor RuntimeExceptionclass. The Java...

4 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Generics in Java

Generics in Java Parameterizedtypes mean generic. Generics allow types (Character, Integer, String, …, etc., as well as user-defined types) to act as parameters to interfaces, classes, and methods. Generics in Java...

9 minutes read.

How to set timer in Java

In this article, you will be very well equipped with the knowledge to set timer in java. The timer in java can be set by using timer class provided by...

3 minutes read.

Prime Points in Java

The points that divide an integer into two halves containing a prime number are known as prime points. Printing every prime point of a specific number is the task. Let's...

6 minutes read.

Add Time in Java

Before Java 8, java.util.Date was one of the most usually involved classes for addressing date-time values in java. Then Java 8 presented java.time.LocalDateTime and java.time.ZonedDateTime. Java 8 likewise permits us...

6 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

What is Core Java?

The fundamental Java, which includes the fundamental idea of the Java programming language, is referred to as "Core Java." The definition of "Core" is the core idea of something. Core...

3 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.