Implement Stack using Array in java

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.
In this post , we will see how to implement Stack using Array in java.
Stack is abstract data type which demonstrates Last in first out (LIFO) behavior. We will implement same behavior using Array.
Although java provides implementation for  all abstract data types such as Stack , Queue and LinkedList but it is always good idea to understand basic data structures and implement them yourself.
Please note that Array implementation of Stack is not dynamic in nature. You can implement Stack through linked list for dynamic behavior.

Java Program to implement Stack using Array:

package org.arpit.java2blog;

 * @author Arpit Mandliya
public class StackCustom {
 int size;
 int arr[];
 int top;

 StackCustom(int size) {
  this.size = size;
  this.arr = new int[size]; = -1;

 public void push(int pushedElement) {
  if (!isFull()) {
   arr[top] = pushedElement;
   System.out.println("Pushed element:" + pushedElement);
  } else {
   System.out.println("Stack is full !");

 public int pop() {
  if (!isEmpty()) {
   int returnedTop = top;
   System.out.println("Popped element :" + arr[returnedTop]);
   return arr[returnedTop];

  } else {
   System.out.println("Stack is empty !");
   return -1;

 public int peek() {
  return arr[top];

 public boolean isEmpty() {
  return (top == -1);

 public boolean isFull() {
  return (size - 1 == top);

 public static void main(String[] args) {
  StackCustom StackCustom = new StackCustom(10);
When you run above program, you will get below output:
Stack is empty !
Pushed element:10
Pushed element:30
Pushed element:50
Pushed element:40
Popped element :40
Popped element :50
Popped element :30
As you can see we have pushed 40 in last, so it is popped first as Stack is of Last In First Out(LIFO) nature.

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus


Java tutorial for beginners Copyright © 2012