Stack Implementation Using Array

Stack is a linear data structure that follows an order i.e LIFO(Last In First Out), where the element which is inserted at the last will come out first.

Basically, there are 4 basic operations that are performed in the stack:

  • Push: Adds an item in the stack.
  • Pop: Removes an item from the stack. The items are popped in the reversed order.
  • Peek: Returns the top element of the stack.
  • isEmpty: Returns true if the stack is empty, else false.

In this example, we’ll see how to implement stack using an array:

1. Java

public class StackImpl {
	int[] stackArray;
	int top;
	public StackImpl(int size) {
		this.stackArray = new int[size]; = -1;
	public void push(int value) {
		stackArray[top] = value;
	public int pop() {
		int topValue = top;
		return stackArray[topValue];
	public int peak() {
		if(isEmpty()) {
			return -1;
		return stackArray[top];
	public boolean isEmpty() {
		return top == -1;


Performing Operations:

public class StackApp {

	public static void main(String[] args) {
		StackImpl stackImpl = new StackImpl(4);

		System.out.println("Removing " + stackImpl.pop());

		System.out.println("Peak Element " + stackImpl.peak());


Removing 40
Peak Element 30

Stack Time Complexity:

The time complexity of the operations performed on Stack totally depends on how you implemented the Stack. Based on the above implementation below is the worst time complexity.

  • Push: O(1) time
  • Pop: O(1) time
  • Peek: O(1) time
  • Size: O(1) time.

Complete Java Solutions can be found here: Github Link

The complete list can be found here: Practise Programming Questions

1 thought on “Stack Implementation Using Array”

Leave a Comment