I have a for loop, and I am not sure how it works. I am familiar with:
for(int i = 0; i <= 9; i++) { /* implementation */ }
I am confused about a for loop in the following form:
String[] myString = new String[] {"one", "two", "three", "some other stuff"}; String str1 = "", str2 = ""; for (String s : myString) { /* implementation */ }
How do these types of for
loops work? what do they do differently then regular for
loops?
In Java, there are three kinds of loops which are – the for loop, the while loop, and the do-while loop. All these three loop constructs of Java executes a set of repeated statements as long as a specified condition remains true.
In Java, there are three types of loops.
There are two types of loops, “while loops” and “for loops”. While loops will repeat while a condition is true, and for loops will repeat a certain number of times. You'll also learn about for each loops which are a type of for loop that repeats once for each item in a list.
The first is the original for loop. You initialize a variable, set a terminating condition, and provide a state incrementing/decrementing counter (There are exceptions, but this is the classic)
For that,
for (int i=0;i<myString.length;i++) { System.out.println(myString[i]); }
is correct.
For Java 5 an alternative was proposed. Any thing that implements iterable can be supported. This is particularly nice in Collections. For example you can iterate the list like this
List<String> list = ....load up with stuff for (String string : list) { System.out.println(string); }
instead of
for (int i=0; i<list.size();i++) { System.out.println(list.get(i)); }
So it's just an alternative notation really. Any item that implements Iterable (i.e. can return an iterator) can be written that way.
What's happening behind the scenes is somethig like this: (more efficient, but I'm writing it explicitly)
Iterator<String> it = list.iterator(); while (it.hasNext()) { String string=it.next(); System.out.println(string); }
In the end it's just syntactic sugar, but rather convenient.
There is an excellent summary of this feature in the article The For-Each Loop. It shows by example how using the for-each style can produce clearer code that is easier to read and write.
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