Stack implementation using Array

Stack is an abstract data type.
Basic operation of stack can be:

1. Push :
Push object on top of stack.
Throw exception if stack is full.

2. Pop :
Take out(remove) object that is on top of stack .
Throw 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:

package datastructure.stack;

public interface Stack {

	//accessor method stack
	public int size();
	public boolean isEmpty();
	public Object top() throws Exception;
	
	//update method stack
	public void push(Object element) throws Exception;
	public Object pop() throws Exception;
}

 

 

 

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

package datastructure.stack;

public class ArrayStack implements Stack {
	
	private Object stack[];
	private int capacity;
	private int currentPos=-1;
	
	public ArrayStack(int capacity){
		this.capacity = capacity;
		stack = new Object[capacity];
	}

	@Override
	public int size() {
		// TODO Auto-generated method stub
		return this.capacity;
	}

	@Override
	public boolean isEmpty() {
		// TODO Auto-generated method stub
		if(currentPos<0){
			return true;
		}
		return false;
	}

	@Override
	public Object top() throws Exception {
		// TODO Auto-generated method stub	
		if(currentPos<0){
			throw new Exception(" Stack is Empty");
		}
		return stack[currentPos];
	}

	@Override
	public void push(Object element) throws Exception {
		// TODO Auto-generated method stub
		if(currentPos==capacity){
			throw new Exception();
		}
		stack[++currentPos] = element;
	}

	@Override
	public Object pop() throws Exception {
		// TODO Auto-generated method stub
		if(currentPos<0){
			throw new Exception();
		}
		return stack[currentPos--] = null;
	}

}

 

 

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.

import datastructure.stack.ArrayStack;

public class MainPractise {

	public static void main(String[] args) {		
		
		ArrayStack as = new ArrayStack(10);  // Stack can have at max 10 element
		try{
			System.out.println("Stack size:"+as.size());
			as.push("Nirav"); // push String object in stack
			as.pop(); // pop Nirav out of stack 🙁
			as.push("Nihar");
			String topString = (String)as.top(); // chek out nihar 😛
			System.out.println(topString); /* U will see stubborn nihar string object 
			                                print out bt the object will still be there */
			
			as.pop(); // Now There is no element in stack
			as.pop(); // it will throw exception as stack is empty
		}catch(Exception e){
			System.out.println("Exception message:"+e.getMessage());
		}
		
	}
}

The output of above code is:

Stack size:10
Nihar
Exception message:Stack is Empty

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 *