How to loop through arrays

Use an enhanced for loop

The enhanced loop reads each value and is ideal when an index is not needed.

int[] scores = {82, 91, 76};
for (int score : scores) {
    System.out.println(score);
}

Use an indexed loop

Use an index when position matters or when updating array elements.

String[] names = {"Ada", "Grace"};
for (int i = 0; i < names.length; i++) {
    System.out.println(i + ": " + names[i]);
}

Calculate a total

A loop can accumulate a result in a variable declared before the loop.

int[] values = {3, 5, 7};
int total = 0;
for (int value : values) {
    total += value;
}
System.out.println(total);

Choose the loop

Prefer enhanced for for read-only traversal. Use an indexed loop for positions, neighboring elements, or replacements.