By Barry Burd

Often, when you are programming in Java, you need a loop — a loop that repeatedly asks the user whether the importantData.txt file should be deleted. The loop continues to ask until the user gives a meaningful response. The loop tests its condition at the end of each iteration, after each of the user’s responses.


That’s why a program has a do loop (also known as a do … while loop). With a do loop, the program jumps right in, executes statements, and then checks a condition. If the condition is true, the program goes back to the top of the loop for another go-around. If the condition is false, the computer leaves the loop (and jumps to whatever code comes immediately after the loop).

The format of a do loop is

do {
} while (Condition)

Writing the Condition at the end of the loop reminds you that the computer executes the Statement inside the loop first. After the computer executes the Statement, the computer goes on to check the Condition. If the Condition is true, the computer goes back for another iteration of the Statement.

With a do loop, the computer always executes the statements inside the loop at least once:

//This code prints something:
int twoPlusTwo = 2 + 2;
do {
 System.out.println("Are you kidding?");
 System.out.println("2+2 doesn't equal 5.");
 System.out.print ("Everyone knows that");
 System.out.println(" 2+2 equals 3.");
} while (twoPlusTwo == 5);

This code displays Are you kidding? 2+2 doesn’t equal 5… and so on and then tests the condition twoPlusTwo == 5. Because twoPlusTwo == 5 is false, the computer doesn’t go back for another iteration. Instead, the computer jumps to whatever code comes immediately after the loop.