Stack implementation in Java using Array - Sample Example

Every software guy requires certain data structures to store a particular type of data. Every programming language of today provides Arrays as fixed sized and easy to use data structure, but as we develop applications we requires more advanced abstractions like stack, queue, list, map...etc.



Although Java Collections provides an in-build support to use these data structures on the fly, but as a programmer we must know actual implementation of these things. In this particular blog we will discuss how to implement Stack in Java using Array. Stack is a commonly used and efficient data structure with a first in last out capability. Lets see how to implement Stack push and pop operations in java using Array.


Stack Implementation in Java using Array

This is a sample program to demonstrate push and pop functionality in Stack in Java.
package com.beingjavaguys.core;  
  
/** 
 * @author Nagesh Chauhan 
 */  
public class StackDemo {  
 private static final int capacity = 3;  
 int arr[] = new int[capacity];  
 int top = -1;  
  
 public void push(int pushedElement) {  
  if (top < capacity - 1) {  
   top++;  
   arr[top] = pushedElement;  
   System.out.println("Element " + pushedElement  
     + " is pushed to Stack !");  
   printElements();  
  } else {  
   System.out.println("Stack Overflow !");  
  }  
 }  
  
 public void pop() {  
  if (top >= 0) {  
   top--;  
   System.out.println("Pop operation done !");  
  } else {  
   System.out.println("Stack Underflow !");  
  }  
 }  
  
 public void printElements() {  
  if (top >= 0) {  
   System.out.println("Elements in stack :");  
   for (int i = 0; i <= top; i++) {  
    System.out.println(arr[i]);  
   }  
  }  
 }  
  
 public static void main(String[] args) {  
  StackDemo stackDemo = new StackDemo();  
  
  stackDemo.pop();  
  stackDemo.push(23);  
  stackDemo.push(2);  
  stackDemo.push(73);  
  stackDemo.push(21);  
  stackDemo.pop();  
  stackDemo.pop();  
  stackDemo.pop();  
  stackDemo.pop();  
 }  
  
} 


Output

If everything goes right you will see following output on console demonstrating all possible cases in Stack Implementation.


In this particular blog we came across 'Stack Implementation in Java using Array '. In upcoming blogs we will see more about general purpose data structures implementations in Java and other open source Technologies..