Mastering Stacks in Java: A Step-by-Step Implementation (Array Based)

Mastering Stacks in Java

Mastering Stacks in Java: A Step-by-Step Implementation (Array Based)

In this tutorial, we’ll implement an Array-Based Stack in Java. The code includes detailed comments to explain what each part does.

Stack implementation in Java code example

Stack Class

// Stack class manages all operations using an array
public class Stack {
    private int[] stackArray;  // Array to hold stack elements
    private int top;           // Index of the top element
    private int capacity;      // Maximum size of the stack

    // Constructor initializes the stack with given capacity
    public Stack(int capacity) {
        this.capacity = capacity;
        this.stackArray = new int[capacity];
        this.top = -1;  // Indicates empty stack
    }

    // Check if the stack is empty
    public boolean isEmpty() {
        return this.top == -1;
    }

    // Check if the stack is full
    public boolean isFull() {
        return this.top == this.capacity - 1;
    }

    // Push an element onto the stack
    public void push(int data) {
        if (isFull()) {
            System.out.println("Stack Overflow: Cannot push " + data);
        } else {
            this.stackArray[++this.top] = data;  // Increment top and add element
        }
    }

    // Pop the top element from the stack
    public int pop() {
        if (isEmpty()) {
            System.out.println("Stack Underflow: Cannot pop from empty stack");
            return -1;  // Or throw exception in real scenarios
        } else {
            return this.stackArray[this.top--];  // Return top and decrement
        }
    }

    // Peek at the top element without removing it
    public int peek() {
        if (isEmpty()) {
            System.out.println("Stack is empty: No element to peek");
            return -1;
        } else {
            return this.stackArray[this.top];  // Return top element
        }
    }

    // Print the Stack
    public void printStack() {
        if (isEmpty()) {
            System.out.println("Stack is Empty");
        } else {
            System.out.print("Stack (top to bottom): ");
            for (int i = this.top; i >= 0; i--) {  // Traverse from top to bottom
                System.out.print(this.stackArray[i] + " ");
            }
            System.out.println();
        }
    }
}

Main Class – Testing the Stack

// Main class to test Stack operations
public class Main {
    public static void main(String[] args) {
        Stack myStack = new Stack(5);  // Create stack with capacity 5

        // Push elements onto the stack
        myStack.push(10);
        myStack.push(20);
        myStack.push(30);
        myStack.printStack();  // Output: Stack (top to bottom): 30 20 10

        // Push one more element
        myStack.push(40);
        myStack.printStack();  // Output: Stack (top to bottom): 40 30 20 10

        // Peek at top
        System.out.println("Top element: " + myStack.peek());  // Output: Top element: 40

        // Pop elements
        myStack.pop();
        myStack.printStack();  // Output: Stack (top to bottom): 30 20 10

        myStack.pop();
        myStack.printStack();  // Output: Stack (top to bottom): 20 10

        // Try to pop from near empty
        myStack.pop();
        myStack.printStack();  // Output: Stack (top to bottom): 10

        // Pop last element
        myStack.pop();
        myStack.printStack();  // Output: Stack is Empty
    }
}

Final Output


Stack (top to bottom): 30 20 10 
Stack (top to bottom): 40 30 20 10 
Top element: 40
Stack (top to bottom): 30 20 10 
Stack (top to bottom): 20 10 
Stack (top to bottom): 10 
Stack is Empty

Conclusion

With comments explaining each step, it’s easier to understand how an Array-Based Stack works internally. By practicing pushes, pops, and peeks, you’ll strengthen your foundation in Data Structures, which is essential for advanced topics like expression evaluation, recursion, and undo mechanisms.

Comments

Popular posts from this blog

Software Engineering Explained: Definition, Process Models, and Challenges

Java Basics – What, Why, and the Real Story

Beginner's Guide to the World Wide Web: Websites, Domains, Networks & More!