Stack Class in Java

Stack Class

A stack is a data structure that implements ‘Last in first out’ (LIFO). It extends the Vector class. Stack performs the push operation for adding the element and pop operation to delete the element from the list.

Example : Program to implement methods available in Stack class

import java.util.*;
public class StackDemo
{
      public static void main(String args[])
      {
            //creating a Stack
            Stack<Object> stack = new Stack<Object>();

            //find the size of element
            System.out.println("Initial size of stack: "+stack.size());
            System.out.println("Stack is empty: "+stack.empty());
  
             //adding the element
             for(char i = 65; i<75; i++)
             {
                  stack.push(i);
             }
             System.out.println("Stack elements are after adding: \n"+stack);
             System.out.println("Size of stack after add: "+stack.size());
             System.out.println("Stack is empty: "+stack.empty());

             //peek element of Stack
             System.out.println("Top element in stack: "+stack.peek());

             //search the Stack element
             System.out.println("Search the elemnt A: "+stack.search('A'));
             System.out.println("Search the element N: "+stack.search('N'));

             // remove the stack elements
             for(char j = 70; j<75; j++)
             {
                   stack.pop();
             }
             System.out.println("Stack elements are after deleting: "+stack);
      }
}


Output:
Initial size of stack: 0
Stack is empty: true
Stack elements are after adding: [A, B, C, D, E, F, G, H, I, J]
Size of stack after add: 10
Stack is empty: false
Top element in stack: J
Search the elemnt A: 10
Search the element N: -1
Stack elements are after deleting: [A, B, C, D, E]