Home » Java programming language

Java Stack search() Method with Example

Stack Class search() method: Here, we are going to learn about the search() method of Stack Class with its syntax and example.
Submitted by Preeti Jain, on March 24, 2020

Stack Class search() method

  • search() method is available in java.util package.
  • search() method is used to search the given object (ob) onto the stack and it returns the position of the given object when it exists.
  • search() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • search() method does not throw an exception at the time of searching the given object.

Syntax:

    public int search(Object ob);

Parameter(s):

  • Object ob – represents the object to be searched in this Stack.

Return value:

The return type of the method is int, it returns the position of the given object.

Example:

// Java program to demonstrate the example 
// of int search(Object ob) method 
// of Stack

import java.util.*;

public class SearchOfStack {
 public static void main(String args[]) {
  // Instantiates Stack object
  Stack s = new Stack();

  // By using push() method isto
  // push the given onto the stack
  s.push(10);
  s.push(20);
  s.push(30);
  s.push(40);
  s.push(50);

  // Display Stack
  System.out.println("s:" + s);

  // By using search() method is
  // to search the element
  // onto the stack and searching starts
  // at index 1
  int index = s.search(30);

  // Display Index 
  System.out.println("s.search(30): " + index);
 }
}

Output

s:[10, 20, 30, 40, 50]
s.search(30): 3



Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.