The java.util.Stack.search(Object element) method in Java is used to search for an element in the stack and get its distance from the top. This method starts the count of the position from 1 and not from 0. The element that is on the top of the stack is considered to be at position 1. If more than one element is present, the index of the element closest to the top is returned. The method returns its position if the element is successfully found and returns -1 if the element is absent.
Parameters: The method accepts one parameter element which refers to the element that is required to be searched for in the Stack.
Return Value: The method returns the position of the element if it is successfully found in the stack (taking the count as base 1) else -1 is returned.
Below programs illustrate the working of java.util.Stack.search() method:
The stack is: [Geeks, 4, Geeks, Welcomes, You] Does the stack contains '4'? 4 Does the stack contains 'Hello'? -1 Does the stack contains 'Geeks'? 3
The stack is: [8, 5, 9, 2, 4] Does the stack contains '9'? 3 Does the stack contains '10'? -1 Does the stack contains '11'? -1
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.