×

Java Queue


What is Queue ?

A queue or FIFO (first in, first out) is an abstract data type that serves as a collection of elements, with two principal operations: enqueue, the process of adding an element to the collection.(The element is added from the rear side) and dequeue, the process of removing the first element that was added. (The element is removed from the front side). It can be implemented by using both array and linked list.

Example :-

import java.util.*;

public class JavaStackDemo {
  public static void main(String[] args)
  {
  //Create an empty Stack
  Stack stack = new Stack();
  
  System.out.println("After Push Operation on Stack :");
  stack.push("first");
  printStackElements(stack);
  stack.push("second");
  printStackElements(stack);
  stack.push("third");
  printStackElements(stack);
  
  System.out.println("\nAfter Pop Operation on Stack :");
  stack.pop();
  printStackElements(stack);
  stack.pop();
  printStackElements(stack);
  stack.pop();
  printStackElements(stack);
  
  
  }
  
  private static void printStackElements(Stack stack)
  {
    if(stack.isEmpty())
    {
      System.out.println("No more items left on the stack");
    }
    else
    {
      System.out.printf("%s\n", stack);
    }
  }
}

Output :-

[first, second, third] 
[second, third] 
second