tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > Collection > Stack > Stack Peek

Stack Peek 

The following example shows how to use Stack.peek API and related operations. Stack provides the following APIs,

public synchronized E peek()
 - Returns the object at top of stack without remove it from stack.   

public E push(E paramE)
 - Pushes an element onto the top of stack. 

public synchronized E pop()
 - Removes the element at top of stack.


File Name  :  
com/bethecoder/tutorials/utils/stack/StackPeek.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.utils.stack;

import java.util.Stack;

public class StackPeek {

  /**
   @param args
   */
  public static void main(String[] args) {

    Stack<String> stack = new Stack<String>();
    stack.push("ONE");
    stack.push("TWO");
    stack.push("THREE");
    stack.push("FOUR");
    System.out.println("Stack : " + stack);
    System.out.println();
    
    //Current top of stack
    System.out.println("Current top of the stack : " + stack.peek());
    
    //Remove the top of stack
    System.out.println("Popped : " + stack.pop());
    
    //Current top of stack
    System.out.println("Current top of the stack : " + stack.peek());
    
    //Remove the top of stack
    System.out.println("Popped : " + stack.pop());
    
    //Current top of stack
    System.out.println("Current top of the stack : " + stack.peek());
    
  }

}
   

It gives the following output,
Stack : [ONE, TWO, THREE, FOUR]

Current top of the stack : FOUR
Popped : FOUR
Current top of the stack : THREE
Popped : THREE
Current top of the stack : TWO



 
  


  
bl  br