Java Loop Through Arrays
Reading one element at a time works, but arrays really shine when you visit every element automatically. Loops let you walk through an entire array with just a few lines of code, no matter how many elements it contains.
Looping with a standard for loop
The classic way to move through an array is a for loop that counts from 0 up to length - 1. The loop variable, often called i, becomes the current index. This approach gives you full control because you always know exactly which position you are looking at.
Printing every element with a for loop
public class Main {
public static void main(String[] args) {
String[] cities = {"Paris", "Tokyo", "Cairo", "Lima"};
for (int i = 0; i < cities.length; i++) {
System.out.println("Index " + i + ": " + cities[i]);
}
}
}Notice the condition uses i < cities.length rather than i <= cities.length. Because the last valid index is one less than the length, stopping before the length keeps you safely inside the array.
Looping with the for-each loop
When you only need the values and not their positions, the for-each loop is cleaner and harder to get wrong. It reads almost like plain English: for each number in the array, do something. There is no counter to manage and no risk of running past the end.
Summing values with a for-each loop
public class Main {
public static void main(String[] args) {
int[] scores = {88, 72, 95, 60};
int total = 0;
for (int score : scores) {
total += score;
}
double average = (double) total / scores.length;
System.out.println("Total: " + total); // 315
System.out.println("Average: " + average); // 78.75
}
}The part before the colon declares a variable that holds a copy of each element in turn, and the part after the colon names the array to walk through. On each pass, score takes the next value from the array.
Which loop should you choose?
- Use a for loop when the index matters or you need to modify elements.
- Use a for-each loop for simple read-only passes over every value.
- Both loops rely on .length staying accurate, so they adapt automatically if the array size changes.