Java: Executing Tasks Until Complete - dummies

Java: Executing Tasks Until Complete

By John Paul Mueller

You can create any looping situation you want in Java by using a for loop. However, working with for loops isn’t always convenient, and you’ll find situations where checking for a condition, rather than taking a precise number of steps, works considerably easier.

Java provides two methods for checking conditions. You can check the condition at the outset of the loop by using the while loop, or you can check the condition at the end of the loop by using a do…while loop. The following sections show how to use both loop types.

As with a for loop, you can use the break and continue statements in either the while loop or do…while loop. The statements work precisely the same way. In addition, you can nest either loop to produce results similar to those shown for the for loop. The main difference in loops is how you define the beginning and end of the loop iterations.

Using the while loop

A while loop checks for a specific condition before it does any work. As long as the condition exists, the loop will continue performing the tasks you assign to it. Because it relies on a condition, the while loop has no specific ending count — you simply wait until a condition changes to end it.

Checking after the first execution with the do…while loop

A do…while loop works almost like a while loop. The difference shows up when the condition is checked. A do…while loop checks the condition at the end of the loop, which means that the loop will always run at least one time.