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



Link to Us
thanks a lot for giving the stack examples