Tuesday, January 14, 2020

while and do-while in Java

The while and do-while statements in Java


The while statement

The while-statements are used for iteration like for-statements in Java. The while loops are complex statements used to repeat a given statement over and over until a predefined condition returns true.

The while- statements are particularly useful when the number of iterations is not known in advance.

Syntax:

while (boolean-expression) {
    statements
}

We can observe the sequence of steps executed in a while-statement in the following diagram.

While-statement
While-statement 

Example:

public class Demo {
     public static void main(String[] args) {
            int test=5;
             while(test>=0)//boolean expression here
             {
              System.out.println("test "+test);
              test--;
             }
            }
}


Output:

test 5
test 4
test 3
test 2
test 1
test 0

The do-while statement

Sometimes, it is more convenient to test the continuation condition at the end of a loop, instead of at the beginning, as is done in the while loop. The do-while statement is very similar to the while statement, except that the word "while" along with the condition that it tests, has been moved to the end. The word "do" is added to mark the beginning of the loop.

The major difference between a while and do-while statement is that the do-while statement must be executed at least once.

Or in other words, the do-while executes one extra loop than while statement loops.

We can observe the sequence of steps executed in a while-statement in the following diagram.

do-while-loop
do-while-loop


Syntax:

do {
    statements
} while ( boolean-expression );

Example:


public class Demo {
     public static void main(String[] args) {
                      int test=5;
                       do
                       {
                        System.out.println("test "+test);
                        test--;
                       }while(test>=0);//boolean expression here
                      }
            }
Output:

test 5
test 4
test 3
test 2
test 1
test 0

Video Tutorial