For future reference, had you typed:
java 7 for loop :
into google, the second result would have helped you. To your defense, if you don't put the "7" there, it would have been more difficult to find a solution (not because it was introduced in java 7, it was in java 5, but because if it's currently supported, then putting a 7 gives you a higher probability of finding up-to-date documentation). This is an example of an enhanced for loop or a for-each loop.
In short:
EnhancedForStatement:
for ( FormalParameter : Expression ) Statement
where the Expression
must be iterable
or an array type.
In simpler terms (array example, but note that anything that implements Iterable
can be used):
String[] words = new String[]{"This","is","the","end"};
for (int i = 0; i < words.length; i++)
{
System.out.println(words[i]);
}
written with a for-each loop is:
for (String s : words)
{
System.out.println(s);
}
If you're wondering about efficiency, check this post out.