Part 1
When I introduce the foreach
loop, I do it the context of a lecture on ArrayLists and wrapper classes. I first just kinda slip it in unannounced:
double total = 0.0;
for (double currentValue : myDoubles)
total += currentValue;
System.out.println(total);
Then we turn to it and begin to break it apart a little. I first compare it to
for (int j = 0; j < myDoubles.size(); j++){
double currentValue = myDoubles.get(j);
. But then I tell the students that there is a hidden limitation. I want to see if they can spot it, and I provide them with three re-writing exercises (that are also practice exercises on the prior concepts) to help them find it:
// Exercise 1:
double total = 0.0;
for (int j = 0; j < myDoubles.size(); j++){
total += myDoubles.get(j);
// Exercise 2:
for (double currentValue : myDoubles)
total += currentValue;
// Exercise 3:
for (int j = 1; j < myDoubles.size(); j++){
if (myDoubles.get(j) < myDoubles(get(j-1))
return false;
return true;
When the last one turns out to be impossible, we discuss the limits imposed by not having a sentinel value.
Part 2
We revisit foreach
loops later in the year when we deal with multi-dimensional arrays. Towards the end of that lesson, they are given this task:
For some int[][] ma, fill every element with the value 3.
We discuss the standard for
loop solution:
for (int y = 0; y < ma.length; y++)
for (int x = 0; x < ma[y].length; x++)
ma[y][x] = 3;
And then I bring them back to foreach
with this pretty-looking thing:
for(int[] outer : ma)
for(int x : outer)
x = 3;
... which, of course, doesn't work at all. I ask the kids to pair up and try to figure out why before we all come back together to have a discussion.
This example brings us right to the heart of copy-by-value (and provides another chance for us to revisit references). I consider the discussion over only when the students seem to understand why the nested foreach
doesn't work, but this loop does:
for(int[] outer : ma)
for(int x=0, x<outer.length; x++)
outer[x] = 3;
foreach
loop if you weren't forced to by your curriculum! $\endgroup$