Representation of a Stack as an Array

Representation of a Stack as an Array in Java

Representation of a Stack as an Array in Java is one of the simplest and most commonly taught ways to understand how stacks work internally.

In this approach, a stack is implemented using a fixed size array along with a variable that keeps track of the top element. This method helps beginners clearly visualize stack operations such as push, pop, and peek while building a strong foundation in data structures and algorithmic thinking.

Representation of a Stack as an Array in Java Programming

What is Stack in Java ?

Stack is a linear data structure that stores elements in a specific order. It follows the Last-In-First-Out (LIFO) principle, the last element added is the first one removed.

You can think of a stack like a stack of plates:

  • You push (add) a plate on top, and
  • You pop (remove) the top plate first.

In programming, you use stacks for tasks like reversing data, parsing expressions, and managing function calls.

Representation of a Stack as an Array in Java

An array is used to store an ordered list of elements. Using an array for representation of stack is one of the easy techniques to manage the data. But there is a major difference between an array and a stack.

  • Size of an array is fixed.
  • While, in a stack, there is no fixed size since the size of stack changed with the number of elements inserted or deleted to and from it.

Following are common operations implemented on the stack:

  • push():When we insert an element in a stack then the operation is known as a push. If the stack is full then the condition is called overflow condition.
  • pop(): When we want to delete an element from the stack, the operation is known as a pop. If the stack is empty means there is no element in the stack, this condition is known as an underflow state.
  • isEmpty():When we want to determines whether the stack is empty or not.
  • isFull(): when we want to determines whether the stack is full or not.’
  • peek(): It returns the element at the given position.

Stack Operations and Logic

Stack using an array typically supports the following operations:

OperationDescription
push(x)Add element x to the top of the stack
pop()Remove and return the element at the top
peek()View the element at the top without removing it
isEmpty()Check if the stack has no elements
isFull()Check if the stack has reached its capacity

Learn DSA

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Different Implementation of Stack as an Array

Algorithm:

1. Push operation : 

  1. If top == capacity – 1, report Stack Overflow (stack full) and stop.
  2. Otherwise, increment top by 1.
  3. Store the value: stack[top] = value.
boolean push (int x)
  {
    if (top >= (MAX - 1))
      {
	System.out.println ("Overflow condition reached");
	return false;
      }
    else
      {
	a[++top] = x;
	System.out.println (x + " pushed into stack");
	return true;
      }
  }

2. Pop Operation

  1. If top == -1, report Stack Underflow (stack empty) and stop.
  2. Otherwise, store poppedValue = stack[top].
  3. Decrement top by 1.
  4. Return poppedValue.
int pop()
    {
        if (top < 0) {
            System.out.println(“Underflow condition reached”);
            return 0;
        }
        else {
            int x = a[top–];
            return x;
        }
    }

3. peek operation:

  1. If top == -1, report stack is empty and stop.
  2. Return stack[top].
int peek()
    {
        if (top < 0) {
            System.out.println(“Underflow condition”);
            return 0;
        }
        else {
            int x = a[top];
            return x;
        }
    }

Java Code to Implement Stack as an Array

Run
/**
 * Representation of a Stack as an Array in Java
 * Demonstrates push, pop, peek, isEmpty, and isFull operations.
 */
import java.util.Scanner;

class ArrayStack {
    private int[] arr;      // Array to store stack elements
    private int top;        // Index of the top element
    private int capacity;   // Max capacity of the stack

    // Constructor to initialize stack
    public ArrayStack(int size) {
        capacity = size;
        arr = new int[capacity];
        top = -1;  // Indicates an empty stack
    }

    // Push operation: add value to stack
    public void push(int value) {
        if (isFull()) {
            System.out.println("Stack Overflow: Cannot push " + value);
        } else {
            arr[++top] = value;
            System.out.println(value + " pushed into stack");
        }
    }

    // Pop operation: remove and return top element
    public int pop() {
        if (isEmpty()) {
            System.out.println("Stack Underflow: No elements to pop");
            return -1;
        } else {
            return arr[top--];
        }
    }

    // Peek operation: return top without removing
    public int peek() {
        if (isEmpty()) {
            System.out.println("Stack is empty");
            return -1;
        }
        return arr[top];
    }

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

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

    // Main method to test stack
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter stack capacity: ");
        int size = sc.nextInt();

        ArrayStack stack = new ArrayStack(size);

        stack.push(10);
        stack.push(20);
        stack.push(30);

        System.out.println("Top element is: " + stack.peek());

        System.out.println("Popped: " + stack.pop());
        System.out.println("Popped: " + stack.pop());

        System.out.println("Top element is now: " + stack.peek());

        sc.close();
    }
}

Input:

Enter stack capacity: 3

Output:

10 pushed into stack
20 pushed into stack
30 pushed into stack
Top element is: 30
Popped: 30
Popped: 20
Top element is now: 10

Representation of Stack as an Array Analysis

Time and Space Complexity for Stack as an Array:

OperationTime ComplexitySpace Complexity
pushO(1)O(1)
popO(1)O(1)
peekO(1)O(1)
isEmptyO(1)O(1)
isFullO(1)O(1)

Note:

  • All operations run in constant time because they involve simple arithmetic and array indexing.
  • Space complexity (additional) is constant, although the array itself uses O(n) space where n is the capacity.

Frequently Asked Questions

Answer:

Using an array provides fast access and simple operations. Array implementation is easy and efficient when stack size is known in advance.

Answer:

This condition is called Stack Overflow. The stack cannot accept new elements if it has reached its capacity.

Answer:

Both push and pop operations run in constant time (O(1)) because they perform simple index updates and value assignments.

Answer:

You use an index variable (top) that starts at -1 and increases with each push or decreases with each pop.

Answer:

Yes, Using structures like ArrayList enables dynamic resizing, avoiding overflow limits. However, that is beyond basic fixed array implementation.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription