Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
stack
peek
communitycreator

What is stack.peek() in Java?

Harris Amjad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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());
}
}

RELATED TAGS

java
stack
peek
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring