Java Arrays Loop

Looping Through an Array

Arrays are great for storing multiple values, and to make the most out of them, you’ll often want to loop through all the elements. The for loop is a classic way to do this. By using the array’s length property, you can ensure your loop runs the correct number of times.

Here’s an example that prints all elements in the vehicles array:

String[] vehicles = {"Toyota", "Honda", "Chevy", "Mazda"};
for (int index = 0; index < vehicles.length; index++) {
  System.out.println(vehicles[index]);
}




Looping Through an Array with For-Each

There’s also a “for-each” loop, which is designed specifically for iterating over arrays and collections. It’s more concise and easier to read compared to the traditional for loop.

The syntax looks like this:

for (type variable : arrayName) {
  // code block to be executed
}

And here’s an example using a for-each loop to print all elements in the vehicles array:

String[] vehicles = {"Toyota", "Honda", "Chevy", "Mazda"};
for (String vehicle : vehicles) {
  System.out.println(vehicle);
}

The code above reads as “for each String element (called vehicle) in the vehicles array, print out the value of vehicle.”




Comparing For Loop and For-Each Loop

When you compare the for loop with the for-each loop, you’ll notice that the for-each method is more straightforward to write, doesn’t require a counter (using the length property), and is generally more readable.

Traditional For Loop Example

String[] vehicles = {"Toyota", "Honda", "Chevy", "Mazda"};
for (int index = 0; index < vehicles.length; index++) {
  System.out.println(vehicles[index]);
}

For-Each Loop Example

String[] vehicles = {"Toyota", "Honda", "Chevy", "Mazda"};
for (String vehicle : vehicles) {
  System.out.println(vehicle);
}
Scroll to Top