Java Program to find if an element is in Stack

Java 8Object Oriented ProgrammingProgramming

The method java.util.Stack.search() is used to find if an element is in the stack or not in Java. This method takes a single parameter i.e. the element that is searched in the stack. It returns the position of the element in the stack(counting from one) if it is available and returns -1 if the element is not available in the stack.

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("Apple");
      stack.push("Mango");
      stack.push("Pear");
      stack.push("Orange");
      stack.push("Guava");
      System.out.println("The stack elements are: " + stack);
      System.out.println("The element Mango is in the stack at position: " + stack.search("Mango"));
      System.out.println("The element Peach is in the stack at position: " + stack.search("Peach"));
   }
}

Output

The stack elements are: [Apple, Mango, Pear, Orange, Guava]
The element Mango is in the stack at position: 4
The element Peach is in the stack at position: -1

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.search() method is used to find if the elements “Mango” and “Peach” are in the stack or not. A code snippet which demonstrates this is as follows −

Stack stack = new Stack();
stack.push("Apple");
stack.push("Mango");
stack.push("Pear");
stack.push("Orange");
stack.push("Guava");
System.out.println("The stack elements are: " + stack);
System.out.println("The element Mango is in the stack at position: " + stack.search("Mango"));
System.out.println("The element Peach is in the stack at position: " + stack.search("Peach"));
raja
Published on 30-Jan-2019 07:29:46
Advertisements