×

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

Java Int Keyword

Among the primitive data types is the Java int keyword. To declare variables, use this. It can also be used with methods that return values of the integer type. It...

3 minutes read.

Java float vs double

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

7 minutes read.

How to run Java Program?

How to run Java Program In this section, we will learn how to write, compile and run a Java program in Command Promptusing notepad. In order to run a Java program, we...

2 minutes read.

POJO in Java

Plain old Java Object, in short, is called POJO in Java. POJO is an everyday object that is not subject to any specific limitations. We can use POJO in any Java...

3 minutes read.

Java Math negateExact() Method

The negateExact() method of Math class returns the negation for the specified argument, throwing an exception if the result overflows an int or a long. Syntax: public static int negateExact (int a)public...

1 minute read.

Java StringReader Class

StreamReader Class technique enables character reading from a string. The java.io package contains this class. A string serves as a source in the character stream. While the Stream class is...

4 minutes read.

Multiple Inheritance Programs in Java

A component of the object-oriented notion known as multiple inheritances allows a class to inherit properties from multiple parent classes. When methods that have the same signature are present in...

4 minutes read.

How to add double quotes in a string in Java

Strings are indicated using double-quotes. Double quotes are not printed; the values inside the double quotes are printed. There are different methods for adding double quotes to the string, such...

2 minutes read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Longest Odd Even Subsequence in Java

In order to solve the Java problem known as the longest odd-even subsequence, one must identify a sequences in a non-negative array having size s that alternately includes odd and...

6 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

3 minutes read.

Reverse a String in Java

Reversing a string means that if we have a string called “what is your name”, the reversed format is “eman ruoy si tahw”. Reversing a string involves totally flipping the...

3 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

Three-way operator in Java

The ternary operator in Java is the only conditional operator that takes three operands. It's a popular one-line substitute for the if-then-else expression among Java programmers. If-else clauses can be...

3 minutes read.

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Java Math cos() Method

The cos() method of Math class returns the trigonometric cosine of the specified angle. Syntax: public static double cos(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The cos() method returns...

1 minute read.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.