Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

new for loop syntax

 
Max Vandenburg
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
while im familiar with the regular for-loop i.e.



i recently come accross a for loop that looked like the following...



the above confuses me, can any one explain how the latter for-loop works?
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The enhanced for-loop is a new construct that does what the foreach construct does in other languages.

It allows you to step through an array or collection without all the syntax of a normal for loop.

Here is an example of using the new for loop.



The first loop says, for each int in the array numbers, print the int.

The second for loops says, for each String in the list, print the String.
 
Mike Noel
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is an enhanced for loop that was introduced with java 5. You can think of it like a foreach (if you're familiar with foreach from scripting languages).

Check out http://java.sun.com/developer/technicalArticles/releases/j2se15langfeat/index.html

for some info on that.
 
Max Vandenburg
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Guys
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Keith Lynn:
It allows you to step through an array or collection without all the syntax of a normal for loop.

s/collection/java.lang.Iterable
Also note that the index is not available within the loop.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic