Thursday, June 28, 2012

Stack Example in Java


Stack is a collection to store data and follows the LIFO (Last In First Out) to remove the elements from it. Following is the implementation of Stack in java.

import java.util.Stack;

public class StackDemo {
      public static void main(String[] args) {       
            Stack<String> stack = new Stack<String>();
            for(int i=0; i<10; i++){
                  stack.push(String.valueOf((i*7)%10));
            }
            System.out.print("\nElements present in Stack (Last In First Out): ");
            for(String str: stack){
                  System.out.print(str + " ");
            }
            System.out.print("\nRemoving Elements from Stack (Last In First Out):");
            while(!stack.isEmpty()){
                  System.out.print(stack.pop() + " ");
            }
      }
}

No comments:

Post a Comment