The better question might be: Why wouldn't you want to use a FOR loop to iterate through an array?
There are many ways to iterate through an Array or a collection and there is no law that states you have to use the FOR loop. In a lot of cases, it's simply the best to use for speed, ease of use, and readability. And yet, in other cases it is not:
The Array:
int[] array = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Display Array with the typical for loop:
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
Display Array with the enhanced for loop:
for(Integer num : array) {
System.out.println(num);
}
Display Array with the do/while loop:
int i = 0;
do {
System.out.println(array[i++]);
} while (i < array.length);
Display Array with the while loop:
int j = 0;
while (j < array.length) {
System.out.println(array[j++]);
}
Display Array through Recursive Iteration:
iterateArray(array, 0); // 0 is the start index.
// The 'iterateArray()' method:
private static int iterateArray(int[] array, int index) {
System.out.println(array[index]);
index++;
if (index == array.length) {
return 0;
}
return iterateArray(array,index);
}
Display Array using Arrays.stream() (Java8+):
Arrays.stream(array).forEach(e->System.out.print(e + System.lineSeparator()));
Display Array using IntStream (Java8+):
IntStream.range(0, array.length).mapToObj(index -> array[index]).forEach(System.out::println);
Choose your desired weapon....