What does the method peek() do in java?


The peek() method is used to look at the object at the top of this stack without removing it from the stack.

Example

import java.util.*;
public class StackDemo {
   public static void main(String args[]) {
     
      Stack st = new Stack();
      st.push("Java");
      st.push("Source");
      st.push("code");
      System.out.println("Top object is: "+st.peek());
   }
}

Output

Top object is: code

Updated on: 25-Feb-2020

179 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements