Stack is a particular kind of abstract data type or collection in which the principal operations on the collection are the addition of an entity to the collection, known as push and removal of an entity, known as pop.
The relation between the push and pop operations is such that the stack is a Last-In-First-Out (LIFO) data structure.In a LIFO data structure, the last element added to the structure must be the first one to be removed.





Program Code :

import java.util.Scanner;
public class Stack{
public static void main(String[] args){
Scanner scn=new Scanner(System.in);
int[] stack=new int[100];
int top=0;
for(;;){
int ch;
System.out.print("\n1. Push\n2. Pop\n3. Display\n4. Exit\n\nEnter your choice\n");
ch=scn.nextInt();
if(ch==1)
{
int items;
if(top==100)
{
System.out.println("Overflow");
}
else
{
System.out.print("\nInput an element in the stack\n");
items=scn.nextInt();
System.out.println(items+" is stored at position "+top);
stack[top++]=items;
}
}
else if(ch==2)
{
if(top==0)
System.out.print("\nUnderflow\n");
else
{
top--;
System.out.println(stack[top]+" has been poped out");
}
}
else if(ch==3)
{
if(top==0)
System.out.println("Stack is empty");
else
{
for(int i=0;i<top;i++)
{
System.out.println(stack[i]);
}
}
}
else if(ch==4)
{
System.exit(0);
}
else
System.out.println("Wrong Input.Please try again...");
}
}
}


Output :

 1. Push
2. Pop
3. Display
4. Exit

Enter your choice
1

Input an element in the stack
123
123 is stored at position 0

1. Push
2. Pop
3. Display
4. Exit

Enter your choice
1

Input an element in the stack
235
235 is stored at position 1

1. Push
2. Pop
3. Display
4. Exit

Enter your choice
3
123
235

1. Push
2. Pop
3. Display
4. Exit

Enter your choice
2
235 has been poped out

1. Push
2. Pop
3. Display
4. Exit

Enter your choice

 
Top