Saturday 10 May 2014

Vector : pop() : Pop Element

public synchronized E pop()
Removes the object at the top of this stack. Returns the removed value.

import java.util.*;

class StackPop{
 public static void main(String args[]){
  Stack<Integer> myStack = new Stack<> ();
  
  /* Add Elements to myStack */
  myStack.add(10);
  myStack.add(20);
  myStack.add(30);
  
  System.out.println("Elements in myStack are");
  System.out.println(myStack);
  
  System.out.println("Calling pop");
  int ele = myStack.pop();
  
  System.out.println(ele + " removed from myStack");
  
  System.out.println("Elements in myStack are");
  System.out.println(myStack);
 }
}

Output
Elements in myStack are
[10, 20, 30]
Calling pop
30 removed from myStack
Elements in myStack are
[10, 20]

1. Throws EmptyStackException if this stack is empty.
import java.util.*;

class StackPopEmptyStack{
 public static void main(String args[]){
  Stack<Integer> myStack = new Stack<> ();
  
  System.out.println("Elements in myStack are");
  System.out.println(myStack);
  
  System.out.print("Calling pop");
  System.out.println(myStack.pop());
 }
}

Output
Elements in myStack are
[]
Calling popException in thread "main" java.util.EmptyStackException
        at java.util.Stack.peek(Stack.java:102)
        at java.util.Stack.pop(Stack.java:84)
        at StackPopEmptyStack.main(StackPopEmptyStack.java:11)


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment