Java do-while loop is a control flow statement and is very similar to a while loop. It is also used to iterate a block of code repeatedly until the boolean condition is true.
The only difference between the java do-while loop and the java while loop is that the do-while loop executes the block of code at least once even if the boolean condition is false but the while loop executes the block of code only when the boolean condition is true.
Example: 1 Write a Java Program to print "Hello" four times using a do-while loop.
public class Main
{
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Hello");
i++;
} while(i < 5);
}
}
Output:
Hello Hello Hello Hello
Example: 2
public class Main
{
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Hello");
i++;
} while(i > 5);
}
}
Output:
Hello
Note: In the above second example, "Hello" is printed only one time because the boolean condition is false and when the boolean condition is false in the do-while loop, the block of code executes at least once.
No comments:
Post a Comment