1. Foreach loops
In the last video, we used `for` loops to repeat code and access every element in a `String` or `array` using an index. Now, let's look at another way to loop, one that's often simpler and easier to read when we want to work with the values in a collection: the `foreach` loop.
2. foreach
A `foreach` loop lets us go through every element in something like an array, without needing to manage the index ourselves. It's especially useful when we don't care where the value is - we just want to do something with each one.
3. foreach syntax
The syntax looks like this:
We start with the keyword for, then declare a temporary variable, here it is name, followed by a colon, and then the array or iterable we're looping through, in this case, names. On each loop, Java gives us the next value from the array and stores it in name, so we can use it inside the loop body.
It reads a lot like English: “for each name in names, do something.”
4. for each loop
This makes foreach loops great for readability as they remove a lot of the extra setup from traditional for loops. But they do come with a tradeoff. Because we're not working with index values, we can't access specific positions, and we can't modify the original array elements directly.
So, if we need to change elements or keep track of their position, a regular for loop is a better choice. But if we're just printing values or doing something with each item as-is, foreach is often the cleaner option.
5. Let's practice!
Next, we’ll use a foreach loop to print the contents of an array, and then switch back to a regular for loop when we need to modify those values. Let’s take a look!