I am fairly new to Java and in another Stack Overflow question about for loops an answer said that there was two uses of for in Java:
for (int i = 0; i < N; i++) {
}
for (String a : anyIterable) {
}
I know the first use of for and have used it a lot, but I have never seen the second one. What is it used to do and when would I use it?
The first of the two you specify is a classic C
forloop. This gives the programmer control over the iteration criteria and allows for three operations: the initialization; the loop test ; the increment expression. Though it is used often to incrementally repeat for a set number of attempts, as in yor example:There are many more instances in code where the
forwas use to iterate over collections:To aleviate the boilerplating of the second type (where the third clause was often unused), and to compliment the Generics introduced in Java 1.5, the second of your two examples – the enhanced for loop, or the
for-each loop– was introduced.The second is used with arrays and Generic collections. See this documentation. It allows you to iterate over a generic collection, where you know the type of the
Collection, without having to cast the result of theIterator.next()to a known type.Compare:
with
This ‘new style’ for loop can be used with arrays as well: