How to find the index of an element in an array in Java?

In this tutorial, we will learn How to find the index of an element in an array in Java? As we know each element in an array is stored at specific locations which we call index numbers and that index number can be found simply by iterating the array as a whole and getting the index number of the desired element.

 index of an element in an array

Index Of An element

The index number in an array is an address of an element in an array where exactly the element is stored to get the address of that element we need to iterate the whole array as the array is stored in sequence and to get the number we need to start from index number zero.

As we can not access the element in an array using the value of elements instant we can access the element by using the index number getting the index number using value is just reversed case so to get the element index we follow a set code which we are going to explain below.

Here is a set of codes that needs to execute to get the index of a given value and solve the problem or to get that element directly by the index we get.

public class index {
 
    // Linear-search function to find the index of an element
    public static int findIndex(int arr[], int t)
    {
 
        // if array is Null
        if (arr == null) {
            return -1;
        }
 
        // find length of array
        int len = arr.length;
        int i = 0;
 
        // traverse in the array
        while (i < len) {
 
            // if the i-th element is t
            // then return the index
            if (arr[i] == t) {
                return i;
            }
            else {
                i = i + 1;
            }
        }
        return -1;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] my_array = { 5, 4, 6, 1, 3, 2, 7, 8, 9 };
 
        // find the index of 5
        System.out.println("Index position of 5 is: "
                           + findIndex(my_array, 5));
 
        // find the index of 7
        System.out.println("Index position of 7 is: "
                           + findIndex(my_array, 7));
    }
}

The above code shows how we can get the index number for a given value.

Learn more about How to find the index of an element in an array in Java? at: Index of an element in array

And also visit Java Tutorials To to learn more about java and solve the problems faced during any problems solving also visit Python Tutorial – Understand Call By Reference | Detailed Guide with Examples To learn more about python and other programming languages.

Leave a Comment

%d bloggers like this: