Java Arrays Loop
Loop Through an Array
You can loop through the array elements with the for
loop,
and use the length
property to specify how many times the loop should run.
This example creates an array of strings and then uses a for
loop to print each element, one by one:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
Here is a similar example with numbers. We create an array of integers and use a for
loop to print each value:
Example
int[] numbers = {10, 20, 30, 40};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Loop Through an Array with For-Each
There is also a "for-each" loop, which is used exclusively to loop through elements in an array (or other data structures):
Syntax
for (type variable : arrayname) {
// code block to be executed
}
The following example uses a for-each loop to print all elements in the cars array:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String car : cars) {
System.out.println(car);
}
This means: for each String
in the cars
array (here called car
), print its value.
Compared to a regular for
loop, the for-each loop is easier to write and read because it does not need a counter (like i < cars.length
).
However, it only gives you the values, not their positions (indexes) in the array.
So, if you need both the position (index) of each element and its value, a regular for
loop is the right choice. For example, when printing seat numbers in a theater row, you need to show both the seat number (the index) and who is sitting there (the value):
Example
String[] seats = {"Jenny", "Liam", "Angie", "Bo"};
for (int i = 0; i < seats.length; i++) {
System.out.println("Seat number " + i + " is taken by " + seats[i]);
}
Note: The for-each loop is great when you only need to read elements.
If you want to change the elements later, or keep track of their index, use a regular for
loop instead.