Java offers three basic types of loops: FOR, WHILE, and DO…WHILE. Their fundamental function is executing a block of code repeatedly, based on a Boolean condition (Farrell, 2014). However, they differ in how they evaluate their conditional expression (Farrell, 2014). A WHILE loop evaluates its conditional expression before executing, therefore, it is possible for this loop to never execute (Farrell, 2014). This property makes it useful in situations where an “out-of-bounds” variable needs to be acted upon, but a definite amount of iterations is unknown, such as when evaluating user input (Farrell, 2014). A FOR loop is similar, but it allows to initialize a variable, a condition, and a statement to be executed as part of the loop declaration, which is generally used to build a counter-controlled loop (Farrell, 2014). A DO…WHILE loop is similar to a WHILE loop, though it evaluates its conditional expression after execution, guaranteeing at least one execution (Farrell, 2014). Although the primary difference between the three kinds of loops is convenience, they all can be used to improve the code’s legibility.
When designing a loop, one can make mistakes that lead to the loop continuing indefinitely. These situations can occur when the loop’s conditional expression can never evaluate to false, such as while (1 == 1), or when the variable critical to this statement is never altered within the loop’s body (Farrell, 2014). Thus, one should ensure that the loop’s termination condition is possible and that the variable that is compared in the conditional expression is altered in the loop (Farrell, 2014). Furthermore, for indefinite loops, adding a failsafe control variable and incrementing it with each iteration is a prudent way of preventing the loop from continuing infinitely.
Reference
Farrell, J. (2014). Java Programming (7th ed.). Boston, MA: Cengage Learning.