A for loop is not always the right tool, and recognising that saves you from forcing a square peg into a round hole.
- You do not know the count in advance. Use a while loop, because a for loop with a made-up bound is just a while loop with extra steps.
- The body must run at least once. Use a do-while loop, since a for loop may run zero times.
- You are traversing data and do not need the index. Use the for-each loop, which has no off-by-one error to make.
- You are transforming a collection. A stream often says what you want far more clearly than an index loop.
And one caution about performance, because it is a common misconception. Writing a tight index loop is not meaningfully faster than a for-each loop, and neither is meaningfully faster than a stream for a small collection. The JVM handles all of these efficiently. Choose the form that reads most clearly, because that is where the real gains are.
Frequently Asked Questions
What does for (;;) do?
It is an infinite loop. All three parts are optional, so with an empty condition Java treats the loop as permanently true and it runs until a break, a return, or an exception stops it. It is a legitimate pattern for a menu loop.
Can the parts of a for loop be left empty?
Yes, any of the three. You can keep only the condition, only the update, or none at all. This is what makes patterns like counting down with a manually managed counter possible, though a while loop is usually clearer for that.
Why is my for loop running forever?
Almost always because the update expression does not move the counter toward the condition, or because you reversed the direction without reversing the condition. Also check for a stray = where you meant ==.
Why does my loop run zero times?
Because the condition was already false on the very first test. A for loop checks the condition before the body, so if the starting value does not satisfy it, nothing runs. Use a do-while if you need one guaranteed pass.
Should I use <= or < with arrays?
Use < with .length, since valid array indices run from zero to length minus one. Using <= is the classic off-by-one that throws an exception on the last pass.
Can I declare the loop variable outside the loop?
You can, but it is not recommended. The variable then survives after the loop and can be misused later by accident. Declaring it in the header keeps its scope tight and lets the compiler catch mistakes.
Is a for loop faster than a while loop?
No, they compile to essentially the same thing. A for loop is preferred for readability, because the counter, the bound and the step sit together in one visible line instead of being split across the method.