Java – Iterate over String Array
To iterate over elements of String Array, use any of the Java Loops like while, for or advanced for loop.
The index of string array starts from 0 to array length – 1. We can use this information and write a loop to iterate over string array elements.
In this tutorial, we will learn how to iterate over string array elements using different looping techniques in Java.
Iterate over String Array using Advanced For Loop
In this example, we will take a string array with four elements and iterate over each of the element using Advanced For Loop in Java.
Java Program
public class Example {
public static void main(String[] args){
String strArr[] = {"aa", "bb", "cc", "dd"};
for(String str: strArr) {
System.out.println(str);
}
}
}
Output
aa
bb
cc
dd
Iterate over String Array using For Loop
In this example, we will take a string array with four elements and iterate over each of the element using For Loop in Java.
Java Program
public class Example {
public static void main(String[] args){
String strArr[] = {"aa", "bb", "cc", "dd"};
for(int i = 0; i < strArr.length; i++) {
String str = strArr[i];
System.out.println(str);
}
}
}
Output
aa
bb
cc
dd
Iterate over String Array using While Loop
In this example, we will take a string array with four elements and iterate over each of the element using While Loop in Java.
Java Program
public class Example {
public static void main(String[] args){
String strArr[] = {"aa", "bb", "cc", "dd"};
int i = 0;
while( i < strArr.length ) {
String str = strArr[i];
System.out.println(str);
i++;
}
}
}
Output
aa
bb
cc
dd
Conclusion
In this Java Tutorial, we learned how to iterate over elements of String Array in Java, with the help of looping statements.