Java Language Basic Control Structures do...while Loop

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The do...while loop differs from other loops in that it is guaranteed to execute at least once. It is also called the "post-test loop" structure because the conditional statement is performed after the main loop body.

int i = 0;
do {
    i++;
    System.out.println(i);
} while (i < 100); // Condition gets checked AFTER the content of the loop executes.

In this example, the loop will run until the number 100 is printed (even though the condition is i < 100 and not i <= 100), because the loop condition is evaluated after the loop executes.

With the guarantee of at least one execution, it is possible to declare variables outside of the loop and initialize them inside.

String theWord;
Scanner scan = new Scanner(System.in);
do {
    theWord = scan.nextLine();
} while (!theWord.equals("Bird"));

System.out.println(theWord);

In this context, theWord is defined outside of the loop, but since it's guaranteed to have a value based on its natural flow, theWord will be initialized.



Got any Java Language Question?