loading

Loop Through an Array

Loop Through an Array

The length attribute allows you to set the number of times the loop should run as you iterate through the members of the array using the for loop.

Every entry in the cars array is output in the example that follows:

Example

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

Loop Through an Array with For-Each

Additionally, there is a “for-each” loop that can only be used to iterate through array elements:

Syntax

				
					for (type variable : arrayname) {
  ...
}
				
			

The “for-each” loop in the example below outputs each element in the cars array:

Example

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

The previous example might be understood as follows: print the value of i for each String element (named i, as in index) in vehicles.

When comparing the for loop with for-each loop, you will see that the for-each approach is more readable, easier to implement, and does not require a counter (by using the length property).

Share this Doc

Loop Through an Array

Or copy link

Explore Topic