Hi there,

I am not good with Java. Can someone explain this for loop for me please. For a for loop, to my understanding the syntax goes something like,

for(int i = 0; i < someNumber; i++) {
     //...some code...

but in this one I have seen, the for loop doesn't have what I expect. What is going on, can someone explain? I found the code on the web, but even with the unfamiliar syntax and without the {} brackets, it seems to compile and work fine.. as a Java project, I think.

What's going on in the second line?

P[] closest = findClosest(points);
for (P p : closest)	

Thank you!

Edited by thompsonSensibl: n/a

5 Years
Discussion Span
Last Post by peter_budo

That's an "enhanced for-each loop" - a new feature in Java 1.5
It uses and array or any other collection (eg List) of things, and iterates thru them one at a time.
In your case closest is an array of "P" objects, and the for loop is read as

for each P object "p" in the array closest...
... print p

Local variable p is set to the first element of closest, and the body of the loop is executed. p is them set to next element etc etc.
It's like

for (int i = 0; i < closest.length; i++) {
  P p = closest[i];

... or the equivalent for collections and lists.

It's generally considered to be an easier and clearer syntax, and it avoids the traps people sometimes fall into with iterators.


As for the lack of parenthesis...
If you are only executing one statement in your for loop,
you don't require the parenthesis.
This is true for most control structures, such as ifs.


Thanks guys :)

If you want to thank them properly you may want to up-vote their replies, and most importantly mark thread as solved, which is bellow of last post in section marked as "Has this thread been answered?" in large purple letters

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.