Java Stack search() Method Example

This example demonstrates the usage of Stack.search() method with an example.
The search() method in Java's Stack class is used to determine whether an object exists in the stack. If the element is found, it returns the 1-based position from the top of the stack. Otherwise, it returns -1.

Java Stack search() Method Example

Let's demonstrate the usage of the search() method with an example:
package com.javaguides.collections.stackexamples;

import java.util.Stack;

public class StackMethodExample {

    public static void main(String[] args) {
        searchMethod();
    }

    private static void searchMethod() {
        // creating stack
        Stack < String > stack = new Stack < > ();

        // populating stack
        stack.push("Java");
        stack.push("JEE");
        stack.push("C");
        stack.push("C++");
        stack.push("Spring");
        stack.push("Hibernate");

        // searching 'Spring' element
        System.out.println("Searching 'Spring' in stack: " + stack.search("Spring"));
    }
}
Output:
Searching 'Spring' in stack: 2

Comments