Do-while Loop
Java Do-while Loop is used to execute a code block repeatedly in a loop based on a condition, with the exception that the code block is executed at least once.
In this tutorial, we will learn the syntax of do-while loop statement and demonstrate some of the scenarios of do-while loop using example programs.
Syntax
The syntax of do-while loop is
do {
statement(s)
} while(condition);
where do and while are Java keywords, statement(s) is a set of valid Java statements, and condition is an expression which must evaluate to a boolean value.
The statement(s) inside the block are executed, and the condition is evaluated. As long as the condition is true, the statement(s) inside the block are executed in a loop; or else if the condition is false, the execution of do-while is completed.
Examples
Simple Do-while Loop
In the following program, we write a do-while loop to print messages in a loop.
Example.java
public class Example {
public static void main(String[] args) {
int i = 0;
do {
System.out.println("hello world " + i);
i++;
} while(i < 4);
}
}
Output
hello world 0
hello world 1
hello world 2
hello world 3
Do-while Loop with Break Statement
We can break a do-while loop using break statement. This breaks the loop even before the condition evaluates to false.
Example.java
public class Example {
public static void main(String[] args) {
int i = 0;
do {
if (i == 3) {
break;
}
System.out.println("hello world " + i);
i++;
} while(i < 8);
}
}
Output
hello world 0
hello world 1
hello world 2
Do-while Loop with Continue Statement
You can skip the execution of code block by using continue statement.
Example.java
public class Example {
public static void main(String[] args) {
int i = 0;
do {
if (i == 3) {
i++;
continue;
}
System.out.println("hello world " + i);
i++;
} while(i < 8);
}
}
Output
hello world 0
hello world 1
hello world 2
hello world 4
hello world 5
hello world 6
hello world 7
Find Factorial using Do-while Loop
In the following java program, we shall find the factorial of a number using do-while loop.
Example.java
public class Example {
public static void main(String[] args) {
int n=6;
//initialization
int factorial = 1;
int i = 1;
do {
factorial = factorial*i;
i++;
} while(i <= n);
System.out.println("Factorial of " + n + " : " + factorial);
}
}
Output
Factorial of 6 : 720
Conclusion
In this Java Tutorial, we learned how to write a do-while loop in Java and covered some of the use cases that use do-while loop.