java.util.Stack.peek() Method


Advertisements


Description

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

Declaration

Following is the declaration for java.util.Stack.peek() method.

public Object peek()

Parameters

NA

Return Value

The method call returns the object at the top of this stack.

Exception

EmptyStackException − This is thrown if this stack is empty.

Example

The following example shows the usage of java.util.Stack.peek()

Live Demo
package com.tutorialspoint;

import java.util.*;

public class StackDemo {
   public static void main(String args[]) {

      // creating stack
      Stack st = new Stack();

      // populating stack
      st.push("Java");
      st.push("Source");
      st.push("code");

      // checking the top object
      System.out.println("Top object is: "+st.peek());
   }     
}

Let us compile and run the above program, this will produce the following result.

Top object is: code

java_util_stack.htm


Advertisements
E-Books Store