I've read an article in the Effective Java about preferring For loops to While loops.
For loops have a lot of advantages over While loops. But is there any disadvantages in preferring For to While?
5 Answers
There is no disadvantage. But for the below case using while loop is more conventional
bool condition = false;
while(!condition)
{
}
1 Comment
The Item 45 (in 2nd Edition of the book) talks about the scope of variables. To minimize the scope of a local variable the while loop has a disadvantage:
boolean condition = false;
while (!condition) {
// do stuff
}
// Here the variable condition still exists
The for loop can limit the visibility
for (boolean condition = false; !condition;) {
// do stuff
}
// Here the variable condition is out of scope and can be garbage collected
This is all that is preferable according to the book.
Comments
For loop is widly used and has more advantages over while loop but ther are some cases when while loop is perferable
Case 1.
when you are playing on booleans. In that case if you are using for loop you explicity define a variable to check or you creat for loop with only condition value in taht case while loop is preferrable
Boolean condition = false;
while(!condition)
{
condition = doSomething();
}
is preferrable then use of
Boolean condition = false;
for(;condition;)
{
condition = doSomething();
}
case 2.
for better visibilty and understanding. When you are working on iterators it is better to use while loop it gives to more clear view of code .
while (iterator.hasNext()) {
String string = (String) iterator.next();
}
Comments
The main advantage of a for loop over a while loop is readability. A For loop is a lot cleaner and a lot nicer to look at. It's also much easier to get stuck in an infinite loop with a while loop. I would say that I agree with your knowledge that if you can use a for loop, you should, so as long as you stick to that, your programming experiences will be much more enjoyable.
Comments
The first thing that comes to mind is JIT optimisations for for loops are easier so more likely to be applied i.e. if we know the number of times a loop will execute then we can unroll it.
Some discussions of loop optimisations and JIT
forloop?forloops andwhileloops are the same.forloop?