do-while Loop
In Java, the do-while loop is a variation of the while loop. The key difference is that the do-while loop guarantees that the block of code is executed at least once, even if the loop condition is initially false. The basic syntax of the do-while loop is as follows:
do {
// Code to be executed
} while (condition);
Example:
public class DoWhileLoopExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println(i);
i++;
} while (i <= 5);
}
}
In this example:
int i = 1;initializes a loop control variableito 1.- The
doblock contains the code to be executed. In this case, it prints the value ofi. i++;increments the value ofiafter each iteration.- The
while (i <= 5);is the loop condition. The loop will continue as long as the condition istrue.
The output of this program will be:
1
2
3
4
5
Even if the condition is initially false, the code inside the do block is executed at least once before checking the condition. This makes the do-while loop suitable when you want to ensure that a certain block of code runs at least once, regardless of the initial condition.
Example with Initially False Condition:
public class DoWhileExample {
public static void main(String[] args) {
int i = 5;
do {
System.out.println("This will be printed at least once.");
} while (i < 3);
}
}
In this case, the message inside the do block will be printed once, even though the condition is initially false.