// Stack class to implement stack operations
private int[] stackArray; // Array to hold stack elements
private int top; // Index of the top element in the stack
private int capacity; // Maximum capacity of the stack
// Constructor to initialize the stack with a given size
stackArray = new int[size]; // Create an array of given size
capacity = size;
top = -1; // Initially, the stack is empty
}
// Push operation: Adds an element to the stack
public void push(int item) {
if (top == capacity - 1) {
System.
out.
println("Stack Overflow. Cannot push " + item
); } else {
stackArray[++top] = item; // Increment top and insert element
System.
out.
println("Pushed: " + item
); }
}
// Pop operation: Removes the top element from the stack
public int pop() {
if (isEmpty()) {
System.
out.
println("Stack Underflow. Cannot pop."); return -1; // Return -1 to indicate stack is empty
} else {
int poppedItem = stackArray[top--]; // Return the top element and decrement top
System.
out.
println("Popped: " + poppedItem
); return poppedItem;
}
}
// Peek operation: Returns the top element of the stack without removing it
public int peek() {
if (isEmpty()) {
System.
out.
println("Stack is empty. Cannot peek."); return -1; // Return -1 if the stack is empty
} else {
System.
out.
println("Top element: " + stackArray
[top
]); return stackArray[top];
}
}
// isEmpty operation: Checks if the stack is empty
public boolean isEmpty() {
return top == -1; // Stack is empty if top is -1
}
// Size operation: Returns the current size of the stack
public int size() {
return top + 1; // The size is the number of elements in the stack
}
}
// Driver class to test stack operations
public class Main {
public static void main
(String[] args
) { Stack stack
= new Stack(5); // Create a stack of capacity 5
// Push some items to the stack
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
// Attempt to push beyond the stack's capacity
stack.push(60);
// Peek at the top element
stack.peek();
// Pop the top element
stack.pop();
// Check if the stack is empty
System.
out.
println("Is the stack empty? " + stack.
isEmpty());
// Get the size of the stack
System.
out.
println("Stack size: " + stack.
size());
// Pop all items from the stack
stack.pop();
stack.pop();
stack.pop();
stack.pop();
// Try to pop from an empty stack
stack.pop();
}
}