00:00

Stack Implementation using Array

Last updated:

In this tutorial, we are going to learn how to implement a stack data structure using an array in Java.

By the end of this tutorial, you will have a clear understanding of stack operations and how to use an array in Java to build a stack. This knowledge will help you to manage data more efficiently.

There are two ways to implement a stack data structure:

  1. Using Array
  2. Using Linked List

Let's see the Stack implementation using Array in Java.

Stack implementation using Array in Java

In an array-based stack implementation, the push operation is implemented by incrementing the index of the top element and storing the new element at that index. The pop operation is implemented by returning the value stored at the top index and decrementing the index.

StackUsingArray.java
class Stack {
  private int array_size = 100; // size of the array
  private int top;              // top of the stack
  private int[] array;          // stack array

  // constructor
  Stack() {
    array = new int[array_size];
    top = -1;
  }

  // Method to check stack is empty or not
  // Returns true if stack is empty else false
  boolean isEmpty() {
    if (top < 0) {
      System.out.println("Stack is empty, cannot pop element.");
      return true;
    }
    return false;
  }

  // Method to check stack is full or not
  // Returns true if stack is full else false
  public boolean isFull() {
    if (top == array_size - 1) {
      System.out.println("Stack is full, cannot push new item.");
      return true;
    }
    return false;
  }

  // Adding new item into the stack
  void push(int item) {
    if (!isFull()) {
      // increment top by 1 and insert item into the array
      array[++top] = item;
      System.out.println(item + " pushed into the stack.");
    }
  }

  // Removing an item from the stack
  void pop() {
    if (!isEmpty()) {
      int item = array[top--];
      System.out.println(item + " popped from the stack.");
    }
  }

  // Returns the top element of the stack.
  void peek() {
    if (!isEmpty()) {
      int item = array[top];
      System.out.println("Stack top item: " + item);
    }
  }

  // Print stack all elements
  void printStack() {
    System.out.print("Stack Items:");
    for (int i = top; i > -1; i--) {
      System.out.print(" " + array[i]);
    }
  }
}

// Driver code
public class StackUsingArray {
  public static void main(String args[]) {
    Stack stack = new Stack();
    stack.push(10);
    stack.push(20);
    stack.push(30);
    stack.push(40);
    stack.pop();
    stack.peek();
    stack.printStack();
  }
}
Output
10 pushed into the stack.
20 pushed into the stack.
30 pushed into the stack.
40 pushed into the stack.
40 popped from the stack.
Stack top item: 30
Stack Items: 30 20 10

Time complexity: O(1) for push, pop, peek, isEmpty and isFull.

Space complexity: O(N), where N is the capacity of the array.