import java.util.*;
public class StackExp {
private int s[], cap, tos;
public StackExp(int cap)
{
s=new int[5];
this.cap=cap;
tos=-1;
}
public void push(int ele)
{
    if(tos==cap-1)
        System.out.println("Stack Overflow");
    else
     {
     tos++;
     s[tos]=ele;
    }
}
public int pop() throws Exception
{
    if(tos==-1)
        throw new Exception("Stack Underflow");
    else
        
        return s[tos--];

 }
}
class Stack
{
    public static void main(String args[]) throws Exception
    {
        StackExp obj=new StackExp(4);
        Scanner src=new Scanner(System.in);
        System.out.println("Enter elements in Stack");
        for(int i=0;i<4;i++)
         obj.push(src.nextInt());
        System.out.println("Elements need to be Popped?");
        int a=src.nextInt();
        System.out.println("Popped out Elements are: -");
        for(int i=0;i<a;i++)
            System.out.println(obj.pop());
    
}
}

Output:-

Enter elements in Stack
2
4
6
9
Elements need to be Popped?
2
Popped out Elements are: -
9
6