Share on Google+Share on Google+

Collection : Stack Example

Advertisement
In this tutorial we will describe implementation of stack with example.

Collection : Stack Example

In this tutorial we will describe implementation of stack with example.

Stack :

Stack is based on concept of LIFO(Last In First Out). It means you can insert elements one by one and at the time of retrieval you will get the last inserted value.
It is subclass of Vector. It has only one access point that is top of stack. There are two main methods of stack to insert and retrieve/delete element of stack that are -
Push() and Pop().

push(Object o) : This method pushes an element at the top of the stack. You can say it is used to insert element to the stack.

pop() : It returns and removes element at the top of the stack. It returns exception EmptyStackException if stack is empty.

Some other methods - empty(), peek(), search(Object o)

Example :

package collection;

import java.util.Stack;

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

// Pushing elements to the stack
stack.push(50);
stack.push("hello");
stack.push("world");
System.out.println("Size of stack : " + stack.size());
System.out.println("Elements of Stack : " + stack);
// Pop operation of stack
System.out.println("Pop element from stack : " + stack.pop());
System.out.println("Pop element from stack : " + stack.pop());
System.out.println("Size of stack : " + stack.size());
}
}

Description : In this example we are implementing stack. For insertion of elements we are using push() method and for displaying and deleting elements ,using pop() method. If you only want to retrieve top of stack element use peek() method.

Output :

Size of stack : 3
Elements of Stack : [50, hello, world]
Pop element from stack : world
Pop element from stack : hello
Size of stack : 1

Advertisements

Advertisement

Posted on: November 20, 2012 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.