Get an element from a Stack in Java without removing it



The Stack is a data structure that is used to store elements in a Last In First Out (LIFO) manner. In Java, a stack is represented by the java.util.Stack class. It provides methods to create and manipulate a stack.

Get an Element of a Stack without Removing it

The pop() method of the Stack class removes the element at the top of the stack and returns it. But there is no direct way to access an element without removing it.

However, we can see/view the top element of a Stack in Java using the peek() method. This method returns the top element of the current Stack (without removing it). It requires no parameters, and if the stack is empty, then it throws an EmptyStackException.

Scenario 1

Input : stack = [1, 2, 3]
Output: 3
Explanation: We added three elements to the stack, and the peek() method returns the top element, which is 3.

Scenario 2

Input : stack = []
Output: EmptyStackException
Explanation: The stack is empty, so calling peek() will throw an EmptyStackException.

Example

Following is an example where we use the peek() method to get an element from a Stack in Java without removing it:

import java.util.Stack;
import java.util.EmptyStackException;

public class StackPeek {
   public static void main(String[] args) {

      Stack <Integer> stack = new Stack<>();

      stack.push(1);
      stack.push(2);
      stack.push(3);

      try {
         int topElement = stack.peek();
         System.out.println("Top element: " + topElement); 
      } catch (EmptyStackException e) {
         System.out.println("Stack is empty, cannot peek.");
      }

      stack.clear();

      try {
         int topElement = stack.peek();
         System.out.println("Top element: " + topElement);
      } catch (EmptyStackException e) {
         System.out.println("Stack is empty, cannot peek."); 
      }
   }
}

When you run the above code, it will output the top element of the stack and handle the case when the stack is empty:

Top element: 3
Stack is empty, cannot peek.
Stack is empty, cannot peek.
Aishwarya Naglot
Aishwarya Naglot

Writing clean code… when the bugs aren’t looking.

Updated on: 2025-07-29T18:46:42+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements