Thursday, January 23, 2025
HomeProgrammingStack peek() Method in Java

Stack peek() Method in Java

In Java, the peek() method is a part of the Stack class, which is a subclass of Vector. The peek() method is used to look at the element at the top of the stack without removing it. It essentially retrieves the item from the stack but leaves the stack unchanged.

Syntax:

Object peek()

Return Value:

  • It returns the object at the top of the stack.
  • If the stack is empty, it throws an EmptyStackException.

Example Usage:

import java.util.Stack;

public class StackExample {
    public static void main(String[] args) {
        Stack<Integer> stack = new Stack<>();

        // Push elements onto the stack
        stack.push(10);
        stack.push(20);
        stack.push(30);

        // Peek at the top element
        System.out.println("Top element is: " + stack.peek()); // Outputs 30

        // Show stack after peeking
        System.out.println("Stack after peek: " + stack); // Stack is unchanged, [10, 20, 30]
        
        // Pop an element to change the stack
        stack.pop();

        // Peek again
        System.out.println("Top element after pop: " + stack.peek()); // Outputs 20
    }
}

Key Points:

  • The peek() method does not modify the stack (no elements are removed).
  • It only provides a view of the top element.
  • It’s a safe way to look at the top element without popping it from the stack.
  • Always be cautious of the EmptyStackException when using peek() on an empty stack.
RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x