0
0
JavaProgramBeginner · 2 min read

Java Program to Implement Stack Using Array

A Java stack using an array can be implemented by creating a class with an array and an integer top pointer, then defining push() to add elements, pop() to remove elements, and display() to show stack contents.
📋

Examples

Inputpush(10), push(20), pop(), display()
OutputPushed 10 Pushed 20 Popped 20 Stack elements: 10
Inputpop() on empty stack
OutputStack Underflow - No elements to pop
Inputpush(5), push(15), push(25), display()
OutputPushed 5 Pushed 15 Pushed 25 Stack elements: 5 15 25
🧠

How to Think About It

To implement a stack using an array, think of the array as a container where you add items on top and remove from the top only. Use a variable called top to track the last added item index. When you push, increase top and store the new item. When you pop, remove the item at top and decrease top. Check for overflow when pushing and underflow when popping.
📐

Algorithm

1
Initialize an array and set top to -1 to indicate an empty stack
2
To push an element, check if the stack is full; if not, increment top and add the element at top
3
To pop an element, check if the stack is empty; if not, remove the element at top and decrement top
4
To display, print all elements from index 0 to top
💻

Code

java
public class Stack {
    private int[] arr;
    private int top;
    private int capacity;

    public Stack(int size) {
        arr = new int[size];
        capacity = size;
        top = -1;
    }

    public void push(int x) {
        if (top == capacity - 1) {
            System.out.println("Stack Overflow - Cannot push " + x);
            return;
        }
        arr[++top] = x;
        System.out.println("Pushed " + x);
    }

    public void pop() {
        if (top == -1) {
            System.out.println("Stack Underflow - No elements to pop");
            return;
        }
        System.out.println("Popped " + arr[top--]);
    }

    public void display() {
        if (top == -1) {
            System.out.println("Stack is empty");
            return;
        }
        System.out.print("Stack elements: ");
        for (int i = 0; i <= top; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Stack stack = new Stack(3);
        stack.push(10);
        stack.push(20);
        stack.pop();
        stack.display();
    }
}
Output
Pushed 10 Pushed 20 Popped 20 Stack elements: 10
🔍

Dry Run

Let's trace pushing 10, pushing 20, popping, and displaying the stack.

1

Initialize stack

Array: [_, _, _], top = -1

2

Push 10

top increments to 0, arr[0] = 10

3

Push 20

top increments to 1, arr[1] = 20

4

Pop element

Element at arr[1] = 20 removed, top decrements to 0

5

Display stack

Print elements from arr[0] to arr[0]: 10

OperationtopArray contents
Initialize-1[_, _, _]
Push 100[10, _, _]
Push 201[10, 20, _]
Pop0[10, 20, _]
Display0[10, 20, _]
💡

Why This Works

Step 1: Tracking top index

The top variable keeps track of the last filled position in the array, starting at -1 when empty.

Step 2: Push operation

When pushing, top increases by 1 and the new element is stored at that index, ensuring LIFO order.

Step 3: Pop operation

Popping removes the element at top and then decreases top, so the stack shrinks from the top.

🔄

Alternative Approaches

Using Linked List
java
class StackNode {
    int data;
    StackNode next;
    StackNode(int d) { data = d; }
}

class Stack {
    StackNode top;

    void push(int x) {
        StackNode node = new StackNode(x);
        node.next = top;
        top = node;
        System.out.println("Pushed " + x);
    }

    void pop() {
        if (top == null) {
            System.out.println("Stack Underflow");
            return;
        }
        System.out.println("Popped " + top.data);
        top = top.next;
    }

    void display() {
        if (top == null) {
            System.out.println("Stack is empty");
            return;
        }
        System.out.print("Stack elements: ");
        StackNode temp = top;
        while (temp != null) {
            System.out.print(temp.data + " ");
            temp = temp.next;
        }
        System.out.println();
    }
}
Linked list stack has dynamic size but uses more memory per element due to node objects.
Using Java's Built-in Stack Class
java
import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();
        stack.push(10);
        stack.push(20);
        System.out.println("Popped " + stack.pop());
        System.out.println("Stack elements: " + stack);
    }
}
Built-in Stack is easy to use but less educational for learning stack internals.

Complexity: O(1) time, O(n) space

Time Complexity

Push and pop operations take constant time O(1) because they only update the top index and array element.

Space Complexity

The stack uses O(n) space where n is the capacity of the array, storing all elements in a fixed-size array.

Which Approach is Fastest?

Array-based stack is fastest for fixed size due to direct indexing; linked list stack is flexible but slightly slower due to node allocation.

ApproachTimeSpaceBest For
Array-based StackO(1)O(n)Fixed size, fast access
Linked List StackO(1)O(n)Dynamic size, flexible memory
Java Built-in StackO(1)O(n)Quick use, less control
💡
Always check for stack overflow before pushing and underflow before popping to avoid errors.
⚠️
Beginners often forget to update the top pointer correctly, causing incorrect push/pop behavior.