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 kamagra cialis kaufen cialis rezeptfrei u.k dissertation motivation source best personal essay editing website for college cause and effect essay on river pollution fluoxetine for pain american history essay questions and answers assisted suicide persuasive essay essay the wars follow advantages and disadvantages of essay test good book review cena cialisa u apoteci go to link best case study editing sites for college see url here sample environmental research paper proscar pharmacy online drug celebrex about teacher short essay source url 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++) {



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]);


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")

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