Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Sunday, 21 July 2013

Queue Implementation in Java using Array - Sample Example

Every software guy requires certain data structures to store a particular type of data. Every programming language of today provides Arrays as fixed sized and easy to use data structure, but as we develop applications we requires more advanced abstractions like stack, queue, list, map...etc.



Although Java Collections provides an in-build support to use these data structures on the fly, but as a programmer we must know actual implementation of these things. In this particular blog we will discuss how to implement queue in Java using Array. Queue is a commonly used and efficient data structure with a first in first out capability. Lets see how to implement Queue push and pop operations in java using Array.


Queue Implementation in Java using Array

This is a sample program to demonstrate push and pop functionality in Queue in Java.
package com.beingjavaguys.core;

/**
 * @author Nagesh Chauhan
 */
public class QueueDemo {
 private static final int capacity = 3;
 int arr[] = new int[capacity];
 int size = 0;
 int top = -1;
 int rear = 0;

 public void push(int pushedElement) {
  if (top < capacity - 1) {
   top++;
   arr[top] = pushedElement;
   System.out.println("Element " + pushedElement
     + " is pushed to Queue !");
   display();
  } else {
   System.out.println("Overflow !");
  }

 }

 public void pop() {
  if (top >= rear) {
   rear++;
   System.out.println("Pop operation done !");
   display();
  } else {
   System.out.println("Underflow !");
  }
 }

 public void display() {
  if (top >= rear) {
   System.out.println("Elements in Queue : ");
   for (int i = rear; i <= top; i++) {
    System.out.println(arr[i]);
   }
  }
 }

 public static void main(String[] args) {
  QueueDemo queueDemo = new QueueDemo();
  queueDemo.pop();
  queueDemo.push(23);
  queueDemo.push(2);
  queueDemo.push(73);
  queueDemo.push(21);
  queueDemo.pop();
  queueDemo.pop();
  queueDemo.pop();
  queueDemo.pop();
 }

}



Output

If everything goes right you will see following output on console demonstrating all possible cases in Queue Implementation.


In this particular blog we came across 'Queue Implementation in Java using Array '. In upcoming blogs we will see more about general purpose data structures implementations in Java and other open source Technologies.







Thanks for reading !
Being Java Guys Team

Download "Queue Implementation in Java Example Project" from "SkyDrive"




8 comments:

  1. IMPROVED VERSION---->>


    import java.util.*;
    class Wonder
    {
    int ele[]=new int[100];
    int size;
    int top;
    int rear;
    Wonder(int limit)
    {
    size=limit;
    top=-1;
    }

    void pushitem(int value) {
    if (top < size - 1) {
    top++;
    ele[top] = value;
    System.out.println("Element " + value
    + " is pushed to Queue !");

    } else {
    System.out.println("Overflow !");
    }

    }

    int popitem() {

    if (top >= rear) {
    int a1=ele[rear];
    rear++;
    System.out.println("Pop operation done !");
    return(a1);
    } else {
    System.out.println("Underflow !");
    return(-9999);
    }

    }

    void printwonder() {
    if (top >= rear) {
    System.out.println("Elements in Queue : ");
    for (int i = rear; i <= top; i++) {
    System.out.println(ele[i]);
    }
    }
    }

    public static void main(String[] args)
    {
    Scanner ob=new Scanner(System.in);
    System.out.println("Enter limit:");
    int l=ob.nextInt();
    Wonder q = new Wonder(l);
    char ch;
    do
    {
    System.out.println("Enter I(Insert)/R(Remove)/D(Display):");
    char x=ob.next().charAt(0);
    x=Character.toUpperCase(x);
    switch(x)
    {
    case 'I':System.out.println("Enter an element:");
    int z=ob.nextInt();
    q.pushitem(z);
    break;
    case 'R':System.out.println("Popped value="+q.popitem());
    break;
    case 'D':q.printwonder();
    break;
    }
    Scanner ob1=new Scanner(System.in);
    System.out.println("Do you want to continue?(Y/N):");
    ch=ob1.next().charAt(0);
    }while(ch=='y'||ch=='Y');
    }
    }

    ReplyDelete
  2. There is a bug is the code.
    Give queue size 2 and perform the following operation.
    1. Push
    2. Push
    3. Pop
    4. Push (It would say overflow)

    ReplyDelete
  3. correct code is:-

    import java.util.Scanner;

    class Que{

    private int size;
    private int front = -1;
    private int rear = -1;
    private Integer[] queArr;

    public Que(int size)
    {
    this.size = size;
    queArr = new Integer[size];

    }


    public void insert(int item)
    {
    if(rear == size-1)
    {
    System.out.println("queue is overflow");

    }
    else if(front==-1)
    {

    rear++;
    queArr[rear] = item;
    front = rear;

    }
    else
    {

    rear++;
    queArr[rear] = item;
    }
    }

    public void delete()
    {
    if(front == -1)
    {
    System.out.println("queue is underflow");

    }
    else if(front==rear)
    {
    System.out.println("removing "+queArr[front]);
    queArr[front] = null;
    front--;
    rear--;

    }
    else
    {
    System.out.println("removing "+queArr[front]);
    queArr[front] = null;
    for(int i=front+1;i<=rear;i++)
    {
    queArr[i-1]=queArr[i];

    }
    rear--;

    }
    }

    public void display()
    {
    if(front==-1)
    System.out.println("queue is empty");
    else
    {
    System.out.println("queue is:");
    for(int i=front;i<=rear;i++)
    {
    System.out.print(queArr[i]+"\t");
    }

    }

    }
    }


    public class TestQueue {

    /**
    * @param args
    */
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("queue test using array");
    Scanner scan = new Scanner(System.in);
    System.out.println("please enter size of queue array");
    int size = scan.nextInt();
    Que que = new Que(size);
    char ch;
    do{

    System.out.println("\nQueue operations \n");
    System.out.println("1. insert");
    System.out.println("2. delete");
    int choice = scan.nextInt();
    switch(choice)
    {
    case 1: System.out.println("enter integer element to insert");
    que.insert(scan.nextInt());
    break;

    case 2:que.delete();
    break;

    }

    que.display();
    System.out.println("\nDo you want to continue (Type y or n) \n");
    ch = scan.next().charAt(0);
    }
    while(ch!='N' || ch!='n');

    }

    }

    ReplyDelete
    Replies
    1. brilliant code .simplest possible explanation of queue implementation in java.
      jus 1 doubt ...why are we doing rear-- again after assigning front to null in delete() function ?

      Delete
  4. public class Queue {

    private int queueSize;
    private int[] queueArray;
    private int front, rear;

    public Queue(int queueSize){
    this.queueSize = queueSize;
    this.queueArray = new int[queueSize];
    front = 0;
    rear = -1;
    }

    public void push(int newData){
    if(rear < this.queueSize-1){
    this.queueArray[++rear] = newData;
    System.out.println("Pushed "+newData);
    }

    else
    System.out.println("Queue full");
    }

    public void pop(){
    if(rear > -1){
    System.out.println("Popped "+this.queueArray[front]);
    for(int i = 0;i<rear;i++){
    this.queueArray[i] = this.queueArray[i+1];
    }
    rear--;
    }
    else
    System.out.println("Queue Empty");
    }

    }

    ReplyDelete
  5. public class que
    {
    int q[];
    int front,rear,size;
    public que(int m)
    {size=m;
    q=new int[size];
    front=rear=-1;
    }
    void insert(int n)
    {
    if(front==0&&rear==size-1)
    {
    System.out.println("over flow");
    System.exit(1);
    }
    else
    {
    if(front==-1)
    front=rear=0;
    else if(rear==size-1)
    rear=0;
    else
    rear++;
    q[rear]=n;
    }
    }
    int remove()
    {
    if(front==-1)
    {
    System.out.println("under flow");
    return -999999;
    }
    else
    {
    int x=q[front];
    if(front==rear)
    front=rear=-1;
    else if(front==size-1)
    front=0;
    else
    front ++;
    return x;
    }
    }
    }

    ReplyDelete
  6. PowerUp Solution17 May 2015 at 09:47

    blog.poweupsolution.com

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft