Java Stack Implementation Simple Example

Recently I started refreshing the backbone of CS, data structure and algorithms. As part of that I wrote a core stack implementation functionalities like Push and Pop in java. I also wrote isEmpty() method just to make use in loops and stuffs like that.

I want you to try writing the stack(LIFO – Last In First Out behaviour) implementation program yourself with these key points,

  1. Create a class named Stack
  2. Have an array to push and pop (store and retrieve).
  3. Have a index variable to keep track on the position.
  4. Create pushIn, PopOut and isEmpty methods.
  5. If you need, you can set the array size dynamically from constructor.

Then from your another main program you can call the constructor with the size or only constructor as per your conclusion on point 5 above.

If you are not going to set dynamically through constructor then you can set the size inside the Stack class only.

== Stop here and try yourself for the solution ==

Java Stack Implementation Simple Example:

Stack Class:

package com.ngdeveloper;

public class Stack {

// item array is to store all the values

    int item[];

    // lastIndex to maintain the current position of the array for push and pop operations.
    int lastIndex;

    public Stack(int arraySize) {
        item = new int[arraySize];
        lastIndex--;
    }

    public int popOut() {
        int temp = lastIndex;
// after the value returned need to decrement, but after return we cant
// so created the temp variable here for the same.
        --lastIndex;
        return item[temp];
    }

    public void pushIn(int newInput) {
        lastIndex++;
        item[lastIndex] = newInput;
    }

    public boolean isEmpty() {
        return (lastIndex == -1);
    }
}

Main class to run and test Stack:

package com.ngdeveloper;

import java.util.Stack;

public class Main {
    public static void main(String[] args) {
        Stack stack = new Stack(10);
        stack.pushIn(12);
        stack.pushIn(27);
        stack.pushIn(3);
        stack.pushIn(7);
        stack.pushIn(19);
        stack.pushIn(19);
        stack.pushIn(19);

        while (!stack.isEmpty()) {
            System.out.println(stack.popOut());
        }
    }
}

Output:

  • While pushing to stack I pushed in this order: 12, 27, 3,7,19,19,19
  • And while retrieving from stack its like below:
19
19
19
7
3
27
12

Leave a Reply