[java] why are there two different kinds of for loops in java?

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?

This question is related to java for-loop

The answer is


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.


The second for loop is any easy way to iterate over the contents of an array, without having to manually specify the number of items in the array(manual enumeration). It is much more convenient than the first when dealing with arrays.


The new for-each loop is just a short hand for the older loop. The new loop is easier to use for arrays and some iterators, but not as flexible, so the old loop has to be using in some situations, like counting from 0 to 9.


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.


Using the first for-loop you manually enumerate through the array by increasing an index to the length of the array, then getting the value at the current index manually.

The latter syntax is added in Java 5 and enumerates an array by using an Iterator instance under the hoods. You then have only access to the object (not the index) and you won't be able to adjust the array while enumerating.

It's convenient when you just want to perform some actions on all objects in an array.


Something none of the other answers touch on is that your first loop is indexing though the list. Whereas the for-each loop is using an Iterator. Some lists like LinkedList will iterate faster with an Iterator versus get(i). This is because because link list's iterator keeps track of the current pointer. Whereas each get in your for i=0 to 9 has to recompute the offset into the linked list. In general, its better to use for-each or an Iterator because it will be using Collections iterator, which in theory is optimized for the collection type.


The for-each loop was introduced in Java 1.5 and is used with collections (and to be pedantic, arrays, and anything implementing the Iterable<E> interface ... which the article notes):

http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html


The For-each loop, as it is called, is a type of for loop that is used with collections to guarantee that all items in a collection are iterated over. For example

for ( Object o : objects ) {
    System.out.println(o.toString());
}

Will call the toString() method on each object in the collection "objects". One nice thing about this is that you cannot get an out of bounds exception.