As you have probably realised by now, the standard for loop, whilst powerful, is a little unwieldy. An alternative method of iteration a foreach loop can be used in some, limited, circumstances. Typically if we have an array we want to iterate through, but not amend the contents of, an Array.
The structure of a foreach loop is as follows
for (TypeOfData nameOfVariable : nameOfArray) {
//do something with nameOfVariable
}
The next example shows two loops, a standard for loop and the equivalent as a foreach loop:
//for loop
for (int i = 0; i < weekDays.length; i++) {
String day = weekDays[i];
System.out.println(day);
}
//foreach loop
for (String day : weekDays) {
System.out.println(day);
}
As you can see the syntax is more succinct, and we avoid possible errors with going out of the bounds of the array that we can experience if we get the for loop syntax wrong. On the downside, we do not know the index of the position of an item in the array, and we cannot change it (changing the 'day' variable in the above example would not change the value stored in the array, only the value of the variable for that iteration of the loop)
String[] words = {"the", "cat", "sat", "on", "the", "mat"};
String phrase = "";
for (int i = 0; i < words.length ; i++) {
phrase += words[i] + " ";
}
System.out.println(phrase.trim());
double total = 0;
double[] hourlyTemperatures = {13.5,14.5,15.0,15.5,16.0,16.5,17.0,17.5,17.0,16.0,15.0,14.0};
for (int i = 0; i < hourlyTemperatures.length; i++) {
total += hourlyTemperatures[i];
}
double average = total / hourlyTemperatures.length;
System.out.println(average);