Conditions choose a branch; loops repeat work while a condition or iteration source permits it.
Java conditions and loops
Working model
Separate a skip condition from a stop condition. continue skips the remaining work for one iteration; break exits the loop. The difference can leave later records unprocessed.
Code
int[] retryCounts = {0, 1, 4, 2};
int acceptedJobs = 0;
for (int retries : retryCounts) {
if (retries > 3) {
continue;
}
acceptedJobs++;
}
System.out.println(acceptedJobs);The output is 3. Each retry count is visited once, so the work is O(n) with O(1) extra space. The enhanced loop fits this case because the code does not need an index.
Cost and design choices
Use a while loop when the number of iterations depends on an external state, but make the state change visible. For bounded retries, a counted loop makes the limit harder to miss.
Loop invariants and exit policies
A loop should make progress toward a condition that can become false. Updating the wrong counter or comparing against an unchanging value can create an infinite loop even when the body appears small.
Use half-open index bounds for arrays: start at zero and stop before length. continue still permits a for loop’s update step, while return exits the method. Do not replace an error with break when the caller needs to know that processing stopped early.
Connected lessons
Continue with Values and control flow, Java Tutorial.
Common Mistakes
A loop ending at index <= array.length accesses one element past the end. Replacing continue with break changes this example to stop at the first rejected record. Unbounded retries can consume resources indefinitely.
