Java – Stack Example

 

Stack class is in java.util package of java. Stack works like last in first out (LIFO) policy. Stack is stack of elements or object which can move the stack. Stack does not require any fix dimension like String array and int array. Stack contains many useful methods. To add element in Stack, we can use push() method of Stack class.

To get value from Stack, Stack provides pop() method and Stack size() method. Size() method returns total number of elements in Stack. peek() method looks at the object at the top of this stack without removing it from the stack

As Stack Class extends Vector class, and when stack is create, it has no elements. Stack class was inserted into java 1.2 and also available java 1.8.

Stack Example

import java.util.Iterator;
import java.util.Stack;

public class StackExample {

    public static void main(String[] args) {

        Stack<String> sk=new Stack<String>();

        sk.push("a");
        sk.push("c");
        sk.push("e");
        sk.push("d");

        Iterator it=sk.iterator();

        System.out.println("Size before pop() :"+sk.size());

        while(it.hasNext())
        {
            String iValue=(String)it.next();
            System.out.println("Iterator value :"+iValue);
        }

        // get and remove last element from stack
        String value =(String)sk.pop();

        System.out.println("value :"+value);

        System.out.println("Size After pop() :"+sk.size());

    }
}

Output

Size before pop() :4
Iterator value :a
Iterator value :c
Iterator value :e
Iterator value :d
value :d
Size After pop() :3

Tags:

 

One Response to “Java – Stack Example”

  1. shezan says:

    thanks a lot for giving the stack examples

Leave a Reply