OneBite.Dev - Coding blog in a bite size

search for a specific element in an array in java

Code snippet on how to search for a specific element in an array in java

public int search(int[] array, int element) { 
  
      for (int i = 0; i < array.length; i++) { 
         if (array[i] == element) 
            return i; 
      } 
  
      return -1; 
} 

The above code snippet searches for a specific element in an array. It takes two parameters – the array of numbers and the element to search for. First, a for-loop is used that iterates through all the elements of the array and checks if it matches with the element to search for. If it is a match, the function returns the index of the element. If no match is found in the array, the function returns -1.

java