What is stack.peek() in Java?

The stack.peek() function in Java is used to get the reference of the element at the top of the stack.

Figure 1 shows the visual representation of the stack.peek() function.

Figure 1: Visual representation of stack.peek() function

The java.util.* module is required in order to use this function.

Syntax

stack_name.peek()
// where the stack_name is the name of the stack

Parameter

This function does not require a parameter.

Return value

stack.peek() is used to get the reference of the element at the stack’s top.

It does not remove that element from the stack.

Code

import java.util.*;
class JAVA {
public static void main( String args[] ) {
Stack<Integer> Stack = new Stack<Integer>();
Stack.add(0);
Stack.add(2);
Stack.add(5);
Stack.add(3);
Stack.add(1);
System.out.println("The stack top element: " + Stack.peek());
}
}

Free Resources