Java Program for Stack Simulation
Program
import java.io.*;
import java.util.*;
public class stack {
private final int size = 10;
private int top;
private int st[];
stack() {
top = -1;
st = new int[5];
}
void push(int item) {
if (top == size) {
System.out.println("Stack overflow");
return;
} else {
st[++top] = item;
System.out.println("Element pushed is:\t" + st[top]);
return;
}
}
void pop() {
if (top == -1) {
System.out.println("Stack underflow");
return;
} else {
System.out.println("Element poped is:\t" + st[top--]);
return;
}
}
void display() {
if (top == -1) {
System.out.println("Stack underflow");
return;
} else {
System.out.println("Contents of stack:");
for (int i = 0; i <= top; i++)
System.out.println(st[i]);
return;
}
}
}
public class StackSimulation {
public static void main(String[] args) {
stack s = new stack();
int choice;
Scanner sc = new Scanner(System.in);
System.out.println("STACK");
while (true) {
System.out.println("1. Push\n2. Pop\n3. Display\n4. Exit");
System.out.println("Enter choice");
choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("Enter the item to push");
int item = sc.nextInt();
s.push(item);
break;
case 2:
s.pop();
break;
case 3:
s.display();
break;
case 4:
sc.close();
System.exit(0);
break;
default:
System.out.println("Invalid choice");
}
}
}
}
Output
STACK
1. Push
2. Pop
3. Display
4. Exit
Enter choice
2
Stack underflow
1. Push
2. Pop
3. Display
4. Exit
Enter choice
1
Enter the item to push
10
Element pushed is: 10
1. Push
2. Pop
3. Display
4. Exit
Enter choice
1
Enter the item to push
20
Element pushed is: 20
1. Push
2. Pop
3. Display
4. Exit
Enter choice
1
Enter the item to push
30
Element pushed is: 30
1. Push
2. Pop
3. Display
4. Exit
Enter choice
3
Contents of stack:
10
20
30
1. Push
2. Pop
3. Display
4. Exit
Enter choice
4