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)	
   System.out.println(p);

Thank you!

Recommended Answers

All 4 Replies

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];
  System.out.println(p);
}

... 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.

Member Avatar for hfx642

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.