For-Each Loop
The last type of loop we want to have a look at is the for-each
loop in Java, for-each
loops are used to iterate over Arrays
or Collections
and provide a more concise and readable way of accessing the elements of these data structures.
Traditional for
Loop Example
Section titled “Traditional for Loop Example”First, let’s look at a traditional for
loop used to iterate over an array:
String[] cars = {"Nissan", "Mazda", "Ford"};for (int i = 0; i < cars.length; i++) { System.out.println(cars[i]);}
In the above code:
- The loop runs for each index of the
cars
array, fromi = 0
toi < cars.length
. - In each iteration, the value at the current index (
cars[i]
) is printed. For example, wheni = 0
,cars[0]
will be"Nissan"
, and the loop will continue printing each car name in the array. - The loop stops when it reaches the last element of the array, ensuring that it doesn’t attempt to access an invalid index.
For-Each Loop
Section titled “For-Each Loop”Now, let’s have a look at the for-each
loop, which is a simplified way to iterate over arrays and collections:
String[] cars = {"Nissan", "Mazda", "Ford"};for (String car : cars){ System.out.println(car)}
In the above code:
- We no longer need to declare the bounds of our loop as the language and syntax is written to know that we want each
car
from our pool ofcars
to return - Will return the exact same results on our first loop
Limitations
Section titled “Limitations”A for-each
loop does have its limitations
- Forward-Only Iteration: The
for-each
loop is designed to iterate over the collection from the first element to the last. It cannot iterate backward like a traditionalfor
loop can (i.e., from the end to the beginning).
- No Access to the Index: In a
for-each
loop, you don’t have direct access to the index of the current element. This means you can’t reference the position of an element, which might be necessary if you need to perform an operation based on the index (e.g., modifying an array or collection at a specific position). - No Modification of Collection Elements: Since we don’t have access to the index, it’s also important to note that you cannot modify the elements of an array or collection in place in a
for-each
loop. You can only access their values.