while and do Loops

The remaining types of loop are while and do. As with for loops, while and do loops enable a block of Java code to be executed repeatedly until a specific condition is met. Whether you use a for, while, or do loop is mostly a matter of your programming style.

while Loops

The while loop is used to repeat a statement as long as a particular condition is true. The following is an example of a while loop:

while (i < 10) {
    x = x * i++; // the body of the loop
}

The condition that accompanies the while keyword is a Boolean expression—i < 10 in the preceding example. If the expression returns true, the while loop executes the body of the loop and then tests the condition again. This process repeats until the condition is false. Although ...

Get Sams Teach Yourself Java 2 in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.