What Is The Stack.peek Method In Java?

The peek method of the Stack class can be used to get the topmost element of a Stack.

Syntax

public E peek()

Return Value

This method returns the topmost element as the return value.

If the Stack is empty then the EmptyStackException is thrown.

Example

import java.util.Stack;
class StackPeekExample {
public static void main( String args[] ) {
// Creating Stack
Stack<Integer> stack = new Stack<>();
// add elememts
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("The Stack is: " + stack);
System.out.println("The peek element is: " + stack.peek());
stack.pop();
System.out.println("The Stack is: " + stack);
System.out.println("The peek element is: " + stack.peek());
}
}

Explanation

In the code above, we have created a Stack object and added three elements 1,2,3 to the Stack using the push method. Then used the peek method to get the topmost element of the Stack.

Free Resources