Stack search() Method in Java
Last Updated :
13 Aug, 2019
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.
Syntax:
STACK.search(element)
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:
Program 1:
import java.util.*;
public class Stack_Demo {
public static void main(String[] args)
{
Stack<String> STACK = new Stack<String>();
STACK.push( "Geeks" );
STACK.push( "4" );
STACK.push( "Geeks" );
STACK.push( "Welcomes" );
STACK.push( "You" );
System.out.println( "The stack is: " + STACK);
System.out.println( "Does the stack contains '4'? "
+ STACK.search( "4" ));
System.out.println( "Does the stack contains 'Hello'? "
+ STACK.search( "Hello" ));
System.out.println( "Does the stack contains 'Geeks'? "
+ STACK.search( "Geeks" ));
}
}
|
Output:
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
Program 2:
import java.util.*;
public class Stack_Demo {
public static void main(String[] args)
{
Stack<Integer> STACK = new Stack<Integer>();
STACK.push( 8 );
STACK.push( 5 );
STACK.push( 9 );
STACK.push( 2 );
STACK.push( 4 );
System.out.println( "The stack is: " + STACK);
System.out.println( "Does the stack contains '9'? "
+ STACK.search( 9 ));
System.out.println( "Does the stack contains '10'? "
+ STACK.search( 10 ));
System.out.println( "Does the stack contains '11'? "
+ STACK.search( 11 ));
}
}
|
Output:
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
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...