Get Index Of Given Element Of Array Using for Loop in Java

There are use cases where you need to get the index of a given element of an Array in Java. To access an array’s element use the index number. Use the length property to determine the number of elements of the Array. The for loop is one of the loops that can be used to loop through an array to retrieve all the elements and their indexes or a single element and its index. In this post, codes to retrieve the all the elements, indexes and their elements and a single required element index are added.

Looping Through An Array Using for Loop

Loop through the array elements with the for loop using the length property to specify how many times the loop should run.

String[] towns = {"Dallas", "Laos", "Austin", "Houston"};
for (int i = 0; i < towns.length; i++) {
  System.out.println(towns[i]);
}

Output:

Dallas
Laos
Austin
Houston

Below is the code if you need to output the index with the element

 String[] towns = {"Dallas", "Laos", "Austin", "Houston"};
for (int i = 0; i < towns.length; i++) {
  System.out.println(i + " : " + towns[i]);
}

Output

0 : Dallas
1 : Laos
2 : Austin
3 : Houston

For the above output, you can display the elements before the indexes. This depends on your use case.

To get the index of a given element of an Array, use this code

 String[] towns = {"Dallas", "Laos", "Austin", "Houston"};
for (int i = 0; i < towns.length; i++) {
  if(towns[i] == "Austin")
  System.out.println(i);
}

The index of element Austin in the code is 2

Feel free to contact me if you have any question on this post or any other one in my blog, I will be glad to help

Leave a Reply