This paste brought to you by Pastebin. View Raw

  1. package org.arpit.java2blog;
  2. public class QueueUsingArrayMain {
  3.  
  4.     private int capacity;
  5.     int queueArr[];
  6.     int front;
  7.     int rear;
  8.     int currentSize = 0;
  9.  
  10.     public QueueUsingArrayMain(int sizeOfQueue) {
  11.         this.capacity = sizeOfQueue;
  12.         front = 0;
  13.         rear = -1;
  14.         queueArr = new int[this.capacity];
  15.     }
  16.  
  17.     /**
  18.      * this method is used to add element in the queue
  19.      *
  20.      * @param data
  21.      */
  22.     public void enqueue(int data) {
  23.         if (isFull()) {
  24.             System.out.println("Queue is full!! Can not add more elements");
  25.         } else {
  26.             rear++;
  27.             if (rear == capacity - 1) {
  28.                 rear = 0;
  29.             }
  30.             queueArr[rear] = data;
  31.             currentSize++;
  32.             System.out.println(data + " added to the queue");
  33.         }
  34.     }
  35.  
  36.     /**
  37.      * This method removes an element from the front of the queue
  38.      */
  39.     public void dequeue() {
  40.         if (isEmpty()) {
  41.             System.out.println("Queue is empty!! Can not dequeue element");
  42.         } else {
  43.             front++;
  44.             if (front == capacity - 1) {
  45.                 System.out.println(queueArr[front - 1] + " removed from the queue");
  46.                 front = 0;
  47.             } else {
  48.                 System.out.println(queueArr[front - 1] + " removed from the queue");
  49.             }
  50.             currentSize--;
  51.         }
  52.     }
  53.  
  54.     /**
  55.      * This method is use to check if element is full or not
  56.      *
  57.      * @return boolean
  58.      */
  59.     public boolean isFull() {
  60.         if (currentSize == capacity) {
  61.             return true;
  62.         }
  63.         return false;
  64.     }
  65.  
  66.     /**
  67.      * This method is use to check if element is empty or not
  68.      *
  69.      * @return
  70.      */
  71.     public boolean isEmpty() {
  72.  
  73.         if (currentSize == 0) {
  74.             return true;
  75.         }
  76.         return false;
  77.     }
  78.  
  79.     public static void main(String a[]) {
  80.  
  81.         QueueUsingArrayMain queue = new QueueUsingArrayMain(5);
  82.         queue.enqueue(6);
  83.         queue.dequeue();
  84.         queue.enqueue(3);
  85.         queue.enqueue(99);
  86.         queue.enqueue(56);
  87.         queue.dequeue();
  88.         queue.enqueue(43);
  89.         queue.dequeue();
  90.         queue.enqueue(89);
  91.         queue.enqueue(77);
  92.         queue.dequeue();
  93.         queue.enqueue(32);
  94.         queue.enqueue(232);
  95.     }
  96. }
  97.