Simple Implemenation Of Stack In Java Using Vector

Stack is a data structure that works on LIFO (Last In First Out) basis. There are mainly two operations in a stack. The ‘push’ operation places the object at the top of the stack, while the ‘pop’ operation removes the object from the top. We might have additional method like ‘peek’ that does not remove the data but simply returns whatever is there at the top of the stack.

Stack data structure can be implemented in Java using a java.util.vector class. The following code demonstrates how simply you can create a LIFO data structure in Java.

package com.kushal.utils;
import java.util.Vector;

public class MyStack {

	Vector myVector;
	public MyStack()
	{
		myVector=new Vector();
	}

	public void push(Object obj)
	{
		myVector.add(obj);

	}

	public Object pop()
	{
		Object obj=null;
		if(myVector.size()>0)
		{
			obj=myVector.elementAt(myVector.size()-1);
			myVector.removeElementAt(myVector.size()-1);
		}
		else
			System.out.println("Stack Underflow");

		return obj;
	}

	public Object peek()
	{
		Object obj=null;
		if(myVector.size()>0)
			obj=myVector.elementAt(myVector.size()-1);
		else
			System.out.println("Stack Underflow");

		return obj;

	}

}

The following is a test class for testing this custom Stack.

public class MyStackTest{
	public static void main(String args [])
	{
		MyStack stack= new MyStack();

		stack.push(new String("One"));
		System.out.println("Added..>"+stack.peek());
		stack.push(new String("Two"));
		System.out.println("Added..>"+stack.peek());
		stack.push(new String("Three"));
		System.out.println("Added..>"+stack.peek());

		System.out.println();
		System.out.println("The top of stack now is... "+stack.peek());
		stack.pop();
		System.out.println("The top of stack now is... "+stack.peek());
		stack.pop();
		System.out.println("The top of stack now is... "+stack.peek());
		stack.pop();
		System.out.println("The top of stack now is... "+stack.peek());
		stack.pop();

	}
}

Sample output of this program is:

Added..>One
Added..>Two
Added..>Three

The top of stack now is… Three
The top of stack now is… Two
The top of stack now is… One
Stack Underflow
The top of stack now is… null
Stack Underflow