VOOZH about

URL: https://www.geeksforgeeks.org/java/stack-peek-method-in-java/

⇱ Stack peek() Method in Java - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Stack peek() Method in Java

Last Updated : 24 Mar, 2025

The java.util.Stack.peek() method in Java is used to retrieve or fetch the first element of the Stack or the element present at the top of the Stack. The element retrieved does not get deleted or removed from the Stack.

Syntax:

STACK.peek()

Parameters: The method does not take any parameters.

Return Value: The method returns the element at the top of the Stack.

Exception: The method throws EmptyStackException if the stack is empty.

Below programs illustrate the java.util.Stack.peek() method:

Program 1:


Output
Initial Stack: [Welcome, To, Geeks, For, Geeks]
The element at the top of the stack is: Geeks
Final Stack: [Welcome, To, Geeks, For, Geeks]

Program 2:


Output
Initial Stack: [10, 15, 30, 20, 5]
The element at the top of the stack is: 5
Final Stack: [10, 15, 30, 20, 5]
Comment