Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Java conditions and loops

Last updated: 29 Sept 20264 min read
tutorial
By AITrove Editorial

Conditions choose a branch; loops repeat work while a condition or iteration source permits it.

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

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

State the loop invariant and exit condition

A loop should keep a condition true after every completed iteration: a processed prefix is valid, a remaining counter is non-negative, or the current search interval contains every possible answer. Naming that condition gives the update and exit test something concrete to preserve.

A continue can skip an update when the update lives in the body. A rejected input can therefore repeat forever if the loop retries without consuming it. A break exits only its defined loop or switch scope, so nested search code needs an explicit result boundary rather than assuming every break leaves the method.

Test the zero-iteration case and the final legal iteration. For an array, the final valid position is length minus one. For a half-open search range, the upper boundary is excluded. Switching between these conventions halfway through a method is a common source of missed values or out-of-bounds access.

java
control-flow
Storage details