Java Arrays Loop: Efficiently Looping Through Arrays Using For Loops
Learn how to loop through array elements in Java using the for
loop. Discover how the length
property helps in determining the number of iterations to efficiently process arrays in your Java programs.
Java Arrays Loop
Loop Through an Array
You can loop through the array elements with the for
loop, using the length
property to specify the number of iterations.
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
Output
Volvo
BMW
Ford
Mazda
Loop Through an Array with For-Each
The "for-each" loop is used to loop through elements in arrays:
Syntax
for (type variable : arrayname) {
// code block to be executed
}
The example below outputs all elements in the cars array using a "for-each" loop:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
Output
Volvo
BMW
Ford
Mazda
The "for-each" loop is easier to write, does not require a counter, and is more readable compared to the traditional for
loop.