For the while statement, if the condition is not met, the loop cannot be entered. But sometimes we need to execute it at least once even if the conditions are not met.
The do...while loop is similar to the while loop, except that the do...while loop will be executed at least once.
do { //code statement}while(Boolean expression);
The do..while loop statement is also called a post-test loop statement. Its loop repetitive execution method also uses a condition to control whether to continue to execute the statement repeatedly. The difference from the while loop is that it first executes the loop statement once and then determines whether to continue execution. For example, calculating the sum of all integers between 1 and 100 can also be achieved using the do...while loop statement. The specific code is as follows:
int sum=0;int i=1;do{sum+=i;i++;} while (i<=100);System.out.println("The sum of all integers between 1 and 100 is: "+sum);
The execution process of the do...while loop statement is: first execute the loop body once, and then judge the conditional expression. If the value of the conditional expression is true, continue execution, otherwise jump out of the loop. In other words, the loop body in the do...while loop statement is executed at least once.
Note: The Boolean expression is after the loop body, so the statement block has been executed before testing the Boolean expression. If the Boolean expression evaluates to true, the statement block is executed until the Boolean expression evaluates to false.
Example
public class Test { public static void main(String args[]){ int x = 10; do{ System.out.print("value of x : " + x ); x++; System.out.print("/n" ); }while( x < 20 ); }}
The compilation and running results of the above example are as follows:
value of x : 10value of x : 11value of x : 12value of x : 13value of x : 14value of x : 15value of x : 16value of x : 17value of x : 18value of x : 19