What is the difference between for, while, and do-while loops in Java?
The primary differences between for, while, and do-while loops in Java are based on their syntax, control flow, and use cases:
For Loop:
Used when the number of iterations is known in advance.
Combines initialization, condition, and increment/decrement in a single statement.
Example:
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
Iterates zero or more times depending on the condition.
While Loop:
Used when the number of iterations is not known, and a condition must be checked before entering the loop body.
Entry-controlled loop: Executes only if the condition is true.
Example:
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
May not execute at all if the condition is false initially.
Do-While Loop:
Ensures the loop body is executed at least once because the condition is checked after executing the loop body.
Exit-controlled loop: Useful when at least one iteration is guaranteed.
Example:
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);