Lesson 20 +10 XP

Loop Through an Array

Loop Through an Array

You often need to visit every element of an array. Java offers two common ways.

For loop with length

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
  System.out.println(cars[i]);
}

This works when you need the index as well as the value.

For each loop

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
  System.out.println(i);
}

This is cleaner when you only need the values.

The difference

LoopBest for
for with indexWhen you need positions
for eachWhen you only need values

Real-world example

Sum up an array of numbers:

int[] numbers = {3, 7, 5};
int sum = 0;
for (int number : numbers) {
  sum += number;
}
System.out.println(sum); // 15

TL;DR

  • Use a counted for loop when you need indexes.
  • Use the for each loop to read values directly.
  • Both work with any array.