Java Stack Implementation using Array

This tutorial gives example of implementing a Stack data structure using Array. The stack offers to put new object on the stack (method push()) and to get objects from the stack (method pop()). A stack returns the object according to last-in-first-out (LIFO). Please note that JDK provides a default java stack implementation as class java.util.Stack.

The two mandatory operations applicable to all stack implementations are:

  • push() : In which a data item is placed at the location pointed to by the stack pointer.
  • pop() : In which a data item is removed and returned from the location pointed to by the stack pointer.

Some environments that rely heavily on stacks may provide additional operations as per requirements. Most common uses of Stack are expression evaluation and syntax parsing. You can find them in undo\redo operations in word processors as well.

Java Stack Implementation Sourcecode

Below program is sample implementation of Stack data structure. Feel free to modify the sourcecode as per your need.

package com.howtodoinjava.datastructure;

import java.util.Arrays;

public class CustomStack <E> 
{
	private int size = 0;
	private static final int DEFAULT_CAPACITY = 10;
	private Object elements[];

	public CustomStack() {
		elements = new Object[DEFAULT_CAPACITY];
	}

	public void push(E e) {
		if (size == elements.length) {
			ensureCapacity();
		}
		elements[size++] = e;
	}

	@SuppressWarnings("unchecked")
	public E pop() {
		E e = (E) elements[--size];
		elements[size] = null;
		return e;
	}

	private void ensureCapacity() {
		int newSize = elements.length * 2;
		elements = Arrays.copyOf(elements, newSize);
	}
	
	@Override
    public String toString()
    {
         StringBuilder sb = new StringBuilder();
         sb.append('[');
         for(int i = 0; i < size ;i++) {
             sb.append(elements[i].toString());
             if(i < size-1){
                 sb.append(",");
             }
         }
         sb.append(']');
         return sb.toString();
    }
}

Now let’s test our Stack implementation by pushing and popping some entries from stack.

public class Main
{
	public static void main(String[] args) 
	{
		CustomStack<Integer> stack = new CustomStack<>();

		stack.push(10);
		stack.push(20);
		stack.push(30);
		stack.push(40);
		
		System.out.println(stack);
		
		System.out.println( stack.pop() );
		System.out.println( stack.pop() );
		System.out.println( stack.pop() );
		
		System.out.println( stack );
	}
}
Output:

[10,20,30,40]
40
30
20
[10]

That’s all for this simple yet important concept about Java Stack Implementation example.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Java Stack Implementation using Array”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.