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?
A "For" Loop is used to repeat a specific block of code a known number of times. For example, if we want to check the grade of every student in the class, we loop from 1 to that number. When the number of times is not known before hand, we use a "While" loop.
Example explainedStatement 1 sets a variable before the loop starts (int i = 0). Statement 2 defines the condition for the loop to run (i must be less than 5). If the condition is true, the loop will start over again, if it is false, the loop will end.
The first of the two you specify is a classic C for
loop. 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:
for (int i=0; i < N : i++)
There are many more instances in code where the for
was use to iterate over collections:
for (Iterator iter = myList.iterator(); iter.hasNext();)
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 the Iterator.next()
to a known type.
Compare:
for(Iterator iter = myList.iterator; iter.hasNext() ; ) { String myStr = (String) iter.next(); //...do something with myStr }
with
for (String myStr : myList) { //...do something with myStr }
This 'new style' for loop can be used with arrays as well:
String[] strArray= ... for (String myStr : strArray) { //...do something with myStr }
The "for in" loop is mostly eye-candy that makes code easier to read. (If you pronounce the : as "in").
I use the second type almost exclusively in my own code whenever I'm iterating over a list or array.
I still use the regular for loop when dealing with mostly mathematical code, or when I need an "i" to see how many times I've looped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With