Java – Stack Example


Stack class is in java.util package of java. Stack works like last in first out policy. 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

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>();


        Iterator it=sk.iterator();

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

            String iValue=(String);
            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());



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



One Response to “Java – Stack Example”

  1. shezan says:

    thanks a lot for giving the stack examples