A Java do-while loop runs its body before testing the condition, so it always executes at least once.
A simple example
Print first, then test
Start withn starts at 1
Do thisPrint n, add 1
ResultStop at 4
The first print happens before the stopping test. The loop prints 1, 2 and 3 on separate lines.Main.java
class Main {
public static void main(String[] args) throws Exception {
int n = 1;
do {
System.out.println(n);
n++;
} while (n <= 3);
}
}
Output
1
2
3
Check a printer until it is ready
A print desk checks the printer once before deciding whether to check again. If the printer answers ready on the second check, the loop stops there. A limit of three checks keeps an offline printer from holding up the desk.
Example: #1 - Simple while Loop
Print the integers from 1 through 5 using a do-while loop.
Java source code
class ControlFlowStatement {
public static void main(String[] args) {
int counter = 1;
do {
System.out.println(counter);
// Increment the number by 1 using Post Increment
counter++;
} while(counter <= 5);
}
}
Output
1
2
3
4
5
Advertisements
Example: #2 - do-while Loop (execute once and terminate)
The initial counter exceeds the limit. The loop still prints it once before the first condition check.
Java source code
class ControlFlowStatement {
public static void main(String[] args) {
int counter = 10;
System.out.println("Execution before while loop");
do {
System.out.println(counter);
// Increment the number by 1 using Post Increment
counter++;
} while(counter <= 5);
System.out.println("Execution after while loop");
}
}
Output
Execution before while loop
10
Execution after while loop
Example: #3 - do-while Loop (Infinite loop)
This example deliberately creates an infinite loop because the counter never changes.
Java source code
class ControlFlowStatement {
public static void main(String[] args) {
int counter = 1;
do {
System.out.println(counter);
} while(counter <= 5);
}
}
Output
1
1
1
.
.
1
Java do-while Loop with break Statement
A break exits the loop immediately.
Example: #4 - do-while Loop with break Statement
Stop after printing 3.
Java source code
class ControlFlowStatement {
public static void main(String[] args) {
int counter = 1;
do {
System.out.println(counter);
// Terminate the execution once counter reached 3
if(counter == 3) {
break;
}
// Increment the number by 1 using Post Increment
counter++;
} while(counter <= 5);
}
}
Output
1
2
3
Java do-while Loop with continue Statement
A continue skips the rest of the current iteration and reaches the next loop test.
Example: #5 - do-while Loop with continue Statement
Skip the iteration for the counter value 3.
Java source code
class ControlFlowStatement {
public static void main(String[] args) {
int counter = 0;
do {
// Increment the number by 1 using Post Increment
counter++;
// skips the iteration once counter reached 3
if(counter == 3) {
continue;
}
System.out.println(counter);
} while(counter <= 5);
}
}