Do While Loop in Java.

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. 

do while loop syntax

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

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS