Stack implementation using Array

Stack is an abstract data type.
The basic operation of the stack can be:

  1. Push :
    Push object on top of stack.
    Throws an exception if a stack is full.

  2. Pop :
    Take out(remove) object that is on top of a stack .
    Throw an exception if stack is empty.

  3. Top:
    Read the object that is on top of stack.
    Throw exception if stack is empty.

Now we need to implement these all operation in Java using Object Array.

Below is my eclipse folder structure. You may find this common but keeping all beginners in mind so please bare with me.

ArrayStack

Lets define an interface for a stack:

Now we need to implement these functionality. So will be implementing this interface by our class called ArrayStack.java.

As you can see in the ArrayStack.java,
we define constructor to initialize the size of our stack. This size will set the limit on number of element in stack.
So let me just briefly explain about class variable and methods.

Object stack[] : An array which is going to be our stack(element holder)
int capacity : Max size of Stack
int currentPos : It is pointer of top element of stack. We will need to increment it when any element is pushed, decrement it when we do the pop operation. Initially we kept it -1 as first element will have index 0. So if there is no element it should be -1.

public int size()                                 : Gives you the capacity of Stack, which was set at the time of initialization.
public boolean isEmpty()                : Gives you true/false based on currentPos pointer.
public Object top()                            : Return the object that is there on top of stack. It does not remove it. And if there is no element that it will                                                                        throw exception.
public void push(Object element) :  Push the object specified as the parameter. If stack is full than it will throw exception.
public Object pop()                           :  Remove the element that is there on top of stack. If stack is empty it will throw the exception.

So thats all everyone. Below is some basic operation that I ran and the output of it.

The output of above code is:

 

This is it.

You can have above code from GIT.

GitHub-Mark-32px https://github.com/Niravkumar-Patel/SnippetExampleRepo.git

If you have any question mail us on
snippetexample@gmail.com or Post comments or join us on facebook.


Leave a Reply

Your email address will not be published. Required fields are marked *