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.
Parameters: The method does not take any parameters.
Return Value: The method returns the element at the top of the Stack else returns NULL if the Stack is empty.
Exception: The method throws EmptyStackException if the stack is empty.
Below programs illustrate the java.util.Stack.peek() method:
Initial Stack: [Welcome, To, Geeks, For, Geeks] The element at the top of the stack is: Geeks Final Stack: [Welcome, To, Geeks, For, Geeks]
Initial Stack: [10, 15, 30, 20, 5] The element at the top of the stack is: 5 Final Stack: [10, 15, 30, 20, 5]
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.