SUNDAY, 12 JULY 2026
Guide For School logo Guide For SchoolStudy Guide For Students On Java Programming
Physics | Chemistry | Mathematics
ICSE | ISC | CBSE
Guide For School logo Guide For SchoolICSE and ISC Resources

Stack Operations Program in Java and Python

21 February 2015

Stack push and pop program with algorithm, explanation, Java solution and simple Python solution for ICSE and ISC students.

Question:

Write a program to implement a stack using an array. The program should allow push, pop and display operations.

A stack follows the LIFO rule: Last In, First Out. Overflow occurs when push is attempted on a full stack, and underflow occurs when pop is attempted on an empty stack.

Stack push operation
Push inserts an element at the top of the stack.
Stack pop operation
Pop removes the element currently stored at the top.
SAMPLE OPERATION TRACE: Create stack of size 5 Push 10 Push 20 Push 30 Pop Display OUTPUT: Popped element: 30 The elements in the stack are: 20 10

Algorithm:

Step 1: Start.

Step 2: Accept the maximum stack size and create array ST.

Step 3: Initialize top = -1 to represent an empty stack.

Step 4: For push, check whether top == size - 1.

Step 5: If the stack is full, display OVERFLOW.

Step 6: Otherwise increase top and store the new value at ST[top].

Step 7: For pop, check whether top == -1.

Step 8: If the stack is empty, display UNDERFLOW and return a sentinel value.

Step 9: Otherwise store ST[top] in a temporary variable and decrease top.

Step 10: For display, print values from top down to 0 so the top element appears first.

Step 11: Repeat menu operations until the user chooses to exit.

Step 12: Stop.

Explanation:

The stack is represented by an array and one pointer variable named top. When the stack is empty, top is set to -1, which is outside the valid array index range.

In the push operation, the program first checks for overflow. If there is space, top is increased before storing the new value, because the new value must occupy the next free position.

In the pop operation, the value at ST[top] is saved before top is decreased. This is necessary because once top moves down, the old top element is no longer considered part of the stack.

Display starts from top and moves down to index 0. This order shows the stack exactly as it is removed: the last inserted element appears first.

The stack works on the LIFO principle, meaning the last value inserted is the first one removed. The program usually maintains a top index to indicate the current topmost element. During push, the top is increased before or after storing the new value depending on the implementation. During pop, the element at the top is removed and the top is decreased. Overflow must be checked before insertion, and underflow must be checked before deletion. These checks are essential because array-based stacks have fixed capacity.

Java Program:

Push Operation:

Java
void push(int n) // Function to insert element in Stack
{
    if(top == size-1) // Condition for Overflow
    {
        System.out.println("OVERFLOW");
    }
    else
    {
        top = top + 1;
        ST[top] = n;
    }
}

Pop Operation:

Java
int pop() // Function to delete element in Stack
{
    if(top == -1) // Condition for Underflow
    {
        System.out.println("UNDERFLOW");
        return -999;
    }
    else
    {
        int val = ST[top]; // Storing the element which will be removed
        top = top - 1;
        return val;
    }
}

Complete Java Program Implementing Operations on Stack:

Java
/**
* The class Stack implements operations of stack using Java
* @author : www.guideforschool.com
* @Program Type : BlueJ Program - Java
*/

class Stack
{
    int ST[]; // Array to implement stack
    int size; // Maximum size of the stack
    int top; // Index of topmost element (Stack Pointer)

    Stack() // Default constructor
    {
        size = 0;
        top = 0;
    }

    Stack(int cap) // Parameterised Constructor
    {
        size = cap;
        ST = new int[size];
        top = -1; // Initialising top with -1
    }

    void push(int n) // Function to insert element in Stack
    {
        if(top == size-1) // Condition for Overflow
        {
            System.out.println("OVERFLOW");
        }
        else
        {
            top = top + 1;
            ST[top] = n; // Storing value in Stack
        }
    }

    int pop() // Function to delete element from Stack
    {
        if(top == -1) // Condition for Underflow
        {
            System.out.println("UNDERFLOW");
            return -999;
        }
        else
        {
            int val = ST[top]; // Storing the element which will be removed
            top = top - 1;
            return val;
        }
    }

    void display()
    {
        if(top == -1)
        {
            System.out.println("The stack is empty");
        }
        else
        {
            System.out.println("The elements in the stack are : ");
            for(int i = top; i>=0; i--)
            {
                System.out.println(ST[i]);
            }
        }
    }
}

Equivalent Python Program:

Python
class StackOperations:
    def __init__(self, cap):
        self.size = cap
        self.ST = [0] * self.size
        self.top = -1

    def push(self, n):
        # top at size - 1 means the stack has no empty position.
        if self.top == self.size - 1:
            print("OVERFLOW")
        else:
            self.top = self.top + 1
            self.ST[self.top] = n

    def pop(self):
        # top equal to -1 means the stack is empty.
        if self.top == -1:
            print("UNDERFLOW")
            return -999

        val = self.ST[self.top]
        self.top = self.top - 1
        return val

    def display(self):
        if self.top == -1:
            print("The stack is empty")
        else:
            print("The elements in the stack are:")
            for i in range(self.top, -1, -1):
                print(self.ST[i], end=" ")
            print()


n = int(input("Enter stack size: "))
ob = StackOperations(n)

# Keep showing the menu until the user selects Exit.
while True:
    print("1. Push  2. Pop  3. Display  4. Exit")
    ch = int(input("Enter your choice: "))

    if ch == 1:
        v = int(input("Enter value to push: "))
        ob.push(v)
    elif ch == 2:
        d = ob.pop()
        if d != -999:
            print("Popped element:", d)
    elif ch == 3:
        ob.display()
    elif ch == 4:
        break
    else:
        print("Invalid choice")

Output:

Enter stack size: 5 1. Push 2. Pop 3. Display 4. Exit Enter your choice: 1 Enter value to push: 10 1. Push 2. Pop 3. Display 4. Exit Enter your choice: 1 Enter value to push: 20 1. Push 2. Pop 3. Display 4. Exit Enter your choice: 2 Popped element: 20 1. Push 2. Pop 3. Display 4. Exit Enter your choice: 3 The elements in the stack are: 10

Leave a Reply

Your email address will not be published. Comments are reviewed before appearing publicly.

Send a comment or correction

Study smarter

Everything you need for ICSE and ISC Computer

Programs, revision notes, solved papers and practical guidance—organized for quick study.

Browse all resources →