The do-while loop is a variation of the while loop. Its syntax is given below:
do { // Loop body; Statement(s); } while (loop-continuation-condition);
Its execution flow chart is shown in Figure 4.4.
The loop body is executed first. Then the loop-continuation-condition is evaluated. If the evaluation is true , the loop body is executed again; if it is false , the do-while loop terminates. The major difference between a while loop and a do-while loop is the order in which the loop-continuation-condition is evaluated and the loop body executed.
The while loop and the do-while loop have equal expressive power. Sometimes one is a more convenient choice than the other. For example, you can rewrite the while loop in Listing 4.2 using a do-while loop, as shown in Listing 4.3.
1 import javax.swing.JOptionPane; 2 3 public class TestDoWhile { 4 /** Main method */ 5 public static void main(String[] args) { 6 int data; 7 int sum = ; 8 9 // Keep reading data until the input is 0 10 do { 11 // Read the next data 12 String dataString = JOptionPane.showInputDialog( null , 13 "Enter an int value:\n(the program exits if the input is 0)" , 14 "TestDo" , JOptionPane.QUESTION_MESSAGE); 15 16 data = Integer.parseInt(dataString); 17 18 sum += data; 19 } while (data != 0); 20 21 JOptionPane.showMessageDialog( null , "The sum is " + sum, 22 "TestDo" , JOptionPane.INFORMATION_MESSAGE); 23 } 24 } |
Tip
Use the do-while loop if you have statements inside the loop that must be executed at least once, as in the case of the do-while loop in the preceding TestDoWhile program. These statements must appear before the loop as well as inside the loop if you use a while loop. |