Create or implement stack using array in java (with example)

By | October 8, 2016
  • Create or implement stack in java using array as underlying data structure.
  • We will create stack class having following methods
    • Push method: Push method will be used to insert new element to stack.
    • Pop method: Pop method will remove top element of stack.
    • Size method: Size method will return current size of stack.
    • isEmpty method: isEmpty method will check, whether stack contains any element.
    • isFull method: isFull method will check, whether stack has exhausted its capacity.

Program – create or implement stack using array in java

1.) Stack class:

  • Stack class composing integer array as underlying data structure.
  • Stack class implements push & pop operations to insert & remove element.
  • Stack class contains utility methods like isEmpty, isFull & size.
package org.learn;

import java.util.EmptyStackException;

public class Stack {

    private int arr[];
    private int size;
    private int index = 0;

    public Stack(int size) {
        this.size = size;
        arr = new int[size];
    }

    public void push(int element) {

        if (isFull()) {
            throw new StackOverflowError("Stack is full");
        }

        arr[index] = element;
        index++;
    }

    public int pop() {

        if (isEmpty()) {
            throw new EmptyStackException();
        }
        return arr[--index];
    }

    public boolean isEmpty() {
        if (index == 0) {
            return true;
        }
        return false;
    }

    public boolean isFull() {
        if (index == size) {
            return true;
        }
        return false;
    }

    public int size() {
        return index;
    }
}

2.) StackClient:

  • StackClient class is client of Stack class.
  • StackClient class will create Stack class & push integers to stack.
  • StackClient class will traverse the stack & pop all elements from stack.
  • We will print size of stack, before & after pop operations.

package org.learn;

public class StackClient {

    public static void main(String[] args) {

        Stack stack = new Stack(5);
        stack.push(5);
        stack.push(4);
        stack.push(3);
        stack.push(2);
        stack.push(1);

        System.out.println("1. Size of stack after push operations: " + stack.size());

        System.out.printf("2. Pop elements from stack : ");
        while (!stack.isEmpty()) {
            System.out.printf(" %d", stack.pop());
        }

        System.out.println("\n3. Size of stack after pop operations : " + stack.size());
    }
}

Output – create or implement stack using array in java


1. Size of stack after push operations: 5
2. Pop elements from stack :  1 2 3 4 5
3. Size of stack after pop operations : 0