Implement push() and pop() operation on Stack

Q. Write a program to implement push() and pop() operation on Stack in Java.

Answer:

A stack is data structure where we can add the element from the top and also remove the element from the top. It follows “Last in first out (LIFO)” principle.

In this example, the push () method is used to add the element in the list and pop () operation is used to remove the top element from the list. The try and catch block is used to handle the EmptyStackException.

StacKDemo.java

import java.util.*;
class  StacKDemo
{
        //porforming push operation
        static void push(Stack st, int a)
        {
                st.push(new Integer(a));
                System.out.println("Element "+a+" push to Stack");
                System.out.println("Stack is: " + st);
        }
        //porforming pop operation
        static void pop(Stack st)
        {
                Integer a = (Integer) st.pop();
                System.out.println("Element "+a+" pop to the stack");
                System.out.println("Stack is: " + st);
        }
        public static void main(String[] args)
        {
                try
                {
                        Stack stack = new Stack();
                        System.out.println("Stack: "+stack);
                        push(stack, 12);
                        push(stack, 15);
                        push(stack, 32);
                        push(stack, 54);
                        pop(stack);
                        pop(stack);
                        pop(stack);
                        pop(stack);
                        pop(stack);
                }
                catch (EmptyStackException ex)
                {
                        System.out.println("Stack is empty");
                }
        }
}


Output:

stack