How to Iterate Through a String Array In Java?

How To Iterate Through a String Array In Java | In this section, we will iterate over the string array elements in Java, as soon as we hear the word iteration the thing that comes to our mind is loops so here we use different types of loops to iterate over the string array. On this page, we use three different types of loops:- for loop, while loop, and advanced for loop that is for each loop.

After iteration the output of the code would be as follows:-
String language[ ] = {“Java”, “Python”, “C++”};

Output:-

Java
Python
C++

Usecases:- In the following programs you will need to iterate through a string array in Java programming language:- Convert String array to Lowercase in Java, Convert String array to UpperCase in Java

Iterate Through a String Array In Java using for loop

The below code is used to iterate over the string array using for loop. The for loop starts from index 0 and continue till the end of the array. For this we need length of the array. The length of an array can be access through using “length” property. See more:- Find length of different arrays in Java.

public class Main {
   public static void main(String[] args) {
      String[] array = { "Java", "Programming", "Language" };

      System.out.println("Iterating array elements using for loop: ");
      for (int i = 0; i < array.length; i++) {
         System.out.println(array[i]);
      }
   }
}

Output:

Iterating array elements using for loop:
Java
Programming
Language

Iterate Through a String Array In Java using while loop

This code is to iterate over the string array using a while loop.

public class Main {
   public static void main(String[] args) {
      String[] array = { "Java", "Programming", "Language" };

      System.out.println("Iterating Array Elements using while loop: ");
      int i = 0;
      while (i < array.length) {
         System.out.println(array[i]);
         i++;
      }
   }
}

Output:-

Iterating Array Elements using while loop:
Java
Programming
Language

Iterate Through a String Array In Java using for-each loop

This code is to iterate over the string array using for each loop that is advanced for loop.

public class Main {
   public static void main(String[] args) {
      String[] array = { "Java", "Programming", "Language" };

      System.out.println("Iterating arrray elements using for each loop: ");
      for (String arrayElements : array) {
         System.out.println(arrayElements);
      }
   }
}

Output:-

Iterating arrray elements using for each loop:
Java
Programming
Language

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *