Stack in Java- Basics

The Stack class represents a last-in-first-out (LIFO) stack of objects. Java has inbuilt objects for stack that offers five basic methods for stack operations.

1) public Object push(Object item)
Pushes an item onto the top of this stack
Parameters:
item – the item to be pushed onto this stack.
Returns:
the item argument.

2) public Object pop()

Removes the object at the top of this stack and returns that object as the value of this function.
Returns:
The object at the top of this stack (the last item of the Vector object).
Throws:
EmptyStackException – if this stack is empty.

3)public Object peek()
Looks at the object at the top of this stack without removing it from the stack.
Returns:
the object at the top of this stack (the last item of the Vector object).
Throws:
EmptyStackException – if this stack is empty.

4)public boolean empty()
Tests if this stack is empty.
Returns:
true if and only if this stack contains no items; false otherwise.

5)public int search(Object o)
Returns the 1-based position where an object is on this stack. If the object o occurs as an item in this stack, this method returns the distance from the top of the stack of the occurrence nearest the top of the stack;
Parameters:
o – the desired object.
Returns:
the 1-based position from the top of the stack where the object is located; the return value -1 indicates that the object is not on the stack.

Sample program:

import java.util.*;

public class stackDemo1
{
public static void main(String[] args) {

Stack pNum = new Stack();
int num;

Scanner in = new Scanner(System.in);
System.out.println("Enter series of number,Enter -1 to break the series ");
int i = 0;
while(in.hasNextInt()) {
num = in.nextInt();
if(num == -1) {
break;
}
else
{
pNum.push(num);
}
} //End of while
System.out.println(pNum);

// Look top most element in stack
System.out.println("Top Element:"+ pNum.peek());

//Search element in stack
//Returns the position of element in stack starting from top
System.out.println("Enter Element to search");
int a = new Scanner(System.in).nextInt();

System.out.println(" Element " + a + " is at "+pNum.search(a));
//empty stack
while(!pNum.empty())
{
pNum.pop();
}
System.out.println("The stack is now empty :" + pNum);

}//End of main()
} // End of class

useful links :

Advertisements

One thought on “Stack in Java- Basics

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s