While often the two constructs are interchangeable, THEY ARE NOT 100% EQUIVALENT!!!
A proof can be constructed by defining // code goes here
that would cause the two constructs to behave differently. One such loop body is:
arr = null;
Therefore, we are now comparing:
char[] arr = new char[5];
for (char x : arr) {
arr = null;
}
with:
char[] arr = new char[5];
for (int i = 0; i < arr.length; i++) {
char x = arr[i];
arr = null;
}
Both code compiles, but if you run them, you will find that the first loop terminates normally, while the second loop will throw a NullPointerException
.
This means that they are not 100% equivalent! There are scenarios where the two constructs will behave differently!
Such scenarios are likely to be rare, but this fact should not be forgotten when debugging, because otherwise you might miss some really subtle bugs.
As an addendum, note that sometimes the for-each construct is not even an option, e.g. if you need the index. The crucial lesson here is that even if it's an option, you need to make sure that it's actually an equivalent substitute, because it's not always guaranteed
Similarly, if you start with a for-each loop and later realized that you need to switch to the indexed for loop, make sure that you're preserving the semantics, because it's not guaranteed.
In particular, _be wary of any modification to the reference of the array/collection being iterated_ (modification to the content may/may not trigger ConcurrentModificationException
, but that's a different issue).
Guaranteeing semantics preservation is also a lot more difficult when you use collections that use custom iterators, but as this example shows, the two constructs are different even when simple arrays are involved.