Originally posted by Stefan Wagner:
Car or boat - which is better and why?
I don't think this is an apt metaphor. For-loops and while-loops are more isomorphic than cars and boats. As demonstrated, you can pretty much use them interchangeably if you structure the code properly. There are definitely things you can do with cars that you can't do with boats, and vice versa.
The choice between the two kinds of loops is mostly a matter of style. I have known people who always use one or the other, but not both. Personally, I typically use for-loops when the number of iterations is known before the loop starts to execute. For instance, I will use 'for' when I am doing operations on a Collection that must be done on every member. (With Java 5, this is actually even better done with the new for-each construct.)
I am more likely to use 'while' if I can't compute the number of iterations in advance. A good example here is when you are processing an arbitrary stream of data and you want to exit the loop when a certain condition is met.
I don't think my way is better than any other, but it reflects the way I think about loop control structures. Because I follow this style consistently, it is easier for me to understand when coming back to code after some time.
Just my 2 cents.
Best,
Rick