Wednesday, 30 November 2016

Program to demonstrate "Stack" class in Java's Collection Framework

The Stack class implements a LIFO (Last In First Out) stack of elements. For example, stack of coins. When you add a new element, it gets stacked on top of the others. When you pull an element off the stack, it removes the element at top. Hence it is called as LIFO (Last In First Out) or FILO (First In Last Out).

Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector and adds several of its own. Stack class has following methods:
  1. boolean empty( ) : Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements.
  2. Object peek( ) : Returns the element on the top of the stack, but does not remove it.
  3. Object pop( ) : Returns the element on the top of the stack, removing it in the process.
  4. Object push(Object element) : Pushes element onto the stack. element is also returned.
  5. int search(Object element) : Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, .1 is returned.

PROGRAM
import java.util.Stack;

class StackDemo {

 public static void main(String[] args) {

  Stack<String> p=new Stack<String>();
  p.push("Apple");
  p.push("Mango");
  p.push("Pine");
  p.push("Orange");
  
  while(!p.empty()) {
   
   System.out.println(p.pop());
  }
 }
}
OUTPUT
C:\>javac StackDemo.java
C:\>java StackDemo
Orange
Pine
Mango
Apple

No comments:

Post a Comment