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) {
		elements[size++] = e;

	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);
    public String toString()
         StringBuilder sb = new StringBuilder();
         for(int i = 0; i < size ;i++) {
             if(i < size-1){
         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<>();

		System.out.println( stack.pop() );
		System.out.println( stack.pop() );
		System.out.println( stack.pop() );
		System.out.println( stack );


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

Happy Learning !!

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial