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.
The
java.util.*
module is required in order to use this function.
stack_name.peek()
// where the stack_name is the name of the stack
This function does not require a parameter.
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.
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());}}