Get an element from a Stack in Java without removing it

Java 8Object Oriented ProgrammingProgramming

The method java.util.Stack.peek() can be used to get an element from a Stack in Java without removing it. This method requires no parameters and it returns the element at the top of the stack. If the stack is empty, then the EmptyStackException is thrown.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Stack;
public class Demo {
   public static void main (String args[]) {
      Stack stack = new Stack();
      stack.push("Amy");
      stack.push("John");
      stack.push("Mary");
      stack.push("Peter");
      stack.push("Susan");
      System.out.println("The stack elements are: " + stack);
      System.out.println("The element at the top of the stack is: " + stack.peek());
   }
}

Output

The stack elements are: [Amy, John, Mary, Peter, Susan]
The element at the top of the stack is: Susan

Now let us understand the above program.

The Stack is created. Then Stack.push() method is used to add the elements to the stack. The stack is displayed and then the Stack.peek() method is used to return the element at the top of the stack and print it. A code snippet which demonstrates this is as follows −

Stack stack = new Stack();
stack.push("Amy");
stack.push("John");
stack.push("Mary");
stack.push("Peter");
stack.push("Susan");
System.out.println("The stack elements are: " + stack);
System.out.println("The element at the top of the stack is: " + stack.peek());
raja
Published on 10-Jan-2019 08:31:37
Advertisements