while and do-while
Description
while checks before the body; do-while checks after.
Explanation
A do-while body always runs at least once.
Example
int i = 1;
while (i <= 3) { i++; }← Chapter 4 — Decision Making & Loops
mixed
Loops repeat code while a condition allows it. Use them for counting, processing arrays, and retrying an action.
Choose the loop that shows your intent. A for loop suits a known count, while a while loop suits repetition that depends on a changing condition.
while checks before the body; do-while checks after.
A do-while body always runs at least once.
int i = 1;
while (i <= 3) { i++; }for keeps setup, condition, and update together.
It is ideal for a counter with a clear range.
for (int i = 1; i <= 3; i++) { }Every loop needs a path toward stopping. Update the counter or state deliberately to avoid an accidental infinite loop.
public class LoopDemo {
public static void main(String[] args) {
for (int lesson = 1; lesson <= 3; lesson++) {
System.out.println("Completed lesson " + lesson);
}
}
}