Comparison of Loop Types in Java: for, for-each, while, and do-while
In Java, loops allow a block of code to run repeatedly based on a condition. Each type of loop is suited for different situations, such as when we know how many times to repeat, want to check a condition before or after running, or simply iterate through a collection.
Java mainly supports four types of loops:
- for loop – Used when the number of iterations is known.
- for-each loop – Used for iterating over arrays or collections.
- while loop – Used when the number of iterations is not known in advance.
- do-while loop – Similar to while, but guarantees one execution.
Comparison Table:
| Feature/Aspect | for Loop | for-each Loop (Enhanced for) | while Loop | do-while Loop |
|---|---|---|---|---|
| Use case | When index/control is needed | When reading elements from array/list | When loop needs to run on a condition | When loop must run at least once |
| Syntax | for (init; cond; update) | for (type var : array) | while (condition) | do { } while (condition); |
| Condition check | Before loop body | Internally handled | Before loop body | After loop body |
| Minimum execution | 0 times (if condition is false) | 0 times (if array is empty) | 0 times (if condition is false) | At least 1 time |
| Accessing index | Yes | No | Yes (if index manually used) | Yes (if index manually used) |
| Best for | Indexed iterations, range-based logic | Reading elements from arrays/collections | Condition-controlled loops | Input/menu that must run once at least |
| Can modify elements? | Yes (using index) | Not directly | Yes | Yes |
| Readable/Simple? | Medium (more code) | Very simple | Medium | Medium |
| Example |
|
|
|
|
Loop Selection Guide
| Situation | Best Loop |
|---|---|
| You need counter/index | for loop |
| You just want to read all values | for-each |
| You want to run while condition is true | while loop |
| You want the loop to run at least once | do-while loop |
Summary :
- for loop – Use when the number of iterations is known and index/control is needed.
- for-each loop – Best for reading elements from arrays/collections; no index access.
- while loop – Use when condition needs to be checked before running; may not run at all.
- do-while loop – Executes loop body at least once; condition is checked after execution.