Java do-while Loop
In this page:
Basic do-while Loop
A do-while loop runs its body first and only checks the condition afterward, at the bottom -- the opposite order from a regular while loop, which tests the condition before ever entering the body.
Example: Basic do-while Loop
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 3);
}
}
Login to try C/C++/Java/PHP code in the editor
Guaranteeing One Run
This ordering guarantees the loop body executes at least once even if the condition would have been false from the very start, which a standard while loop can never guarantee.
Example: Guaranteeing One Run
public class Main {
public static void main(String[] args) {
int i = 10;
do {
System.out.println("Runs once: " + i);
} while (i < 5);
}
}
Login to try C/C++/Java/PHP code in the editor
Incrementing Variables inside Loop
You must modify the variable checked in your loop condition somewhere inside the do-while block, or the loop keeps repeating forever since the condition never has a chance to become false.
Example: Incrementing Variables inside Loop
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++; // without this, the loop never ends
} while (i < 3);
}
}
Login to try C/C++/Java/PHP code in the editor
Simulated Interactive Runs
Just like any loop, you must update the variable the condition depends on somewhere inside the do-while body -- if that variable never changes, the loop will run forever once it starts.
Example: Simulated Interactive Runs
public class Main {
public static void main(String[] args) {
int attempts = 0;
do {
attempts++;
System.out.println("Attempt " + attempts);
} while (attempts < 3);
}
}
Login to try C/C++/Java/PHP code in the editor
Nested do-while Loops
Nesting a do-while inside another do-while lets you build structures like a grid where each outer iteration always processes at least one full pass of the inner loop, guaranteed.
Example: Nested do-while Loops
public class Main {
public static void main(String[] args) {
int row = 1;
do {
int col = 1;
do {
System.out.print(col + " ");
col++;
} while (col <= 3);
System.out.println();
row++;
} while (row <= 2);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: