Java Utility Library

Java Stack - peek() Method



The java.util.Stack.peek() method returns the top element of the stack (the last item of the stack).

This method has same effect as lastElement method.

Syntax

public E peek()

Here, E is the type of element maintained by the container.


Parameters

No parameter is required.

Return Value

Returns the top element of the stack (the last item of the stack).

Exception

Throws EmptyStackException, the stack is empty.

Example:

In the example below, the java.util.Stack.peek() method is used to add a new element at the top of the stack called MyStack.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a stack
    Stack<Integer> MyStack = new Stack<Integer>();

    //populating stack
    MyStack.push(10);
    MyStack.push(20);
    MyStack.push(30);
    MyStack.push(40);

    System.out.print("MyStack contains: ");
    while(MyStack.size() != 0) {
      System.out.print(MyStack.peek()+ " ");
      MyStack.pop();
    }
  }
}

The output of the above code will be:

MyStack contains: 40 30 20 10 

❮ Java.util - Stack