Saturday 10 May 2014

Stack : peek : Get the top element of the Stack

public synchronized E peek()
Return the object at the top of this stack

import java.util.*;

class StackPeek{
 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.print("Top Element of myStack is ");
  System.out.println(myStack.peek());
 }
}

Output
Elements in myStack are
[10, 20, 30]
Top Element of myStack is 30

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

class StackPeekEmptyStack{
 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("Top Element of myStack is ");
  System.out.println(myStack.peek());
 }
}

Output
Elements in myStack are
[]
Top Element of myStack is Exception in thread "main" java.util.EmptyStackException
        at java.util.Stack.peek(Stack.java:102)
        at StackPeekEmptyStack.main(StackPeekEmptyStack.java:11)




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment