Java Looping Statements – Complete Guide with For, While, and Do-While Loops
Learn all types of loops in Java, including for, while, do-while, nested loops, and best practices with examples for beginners and advanced usage.
Looping Statements in Java – Complete Detailed Tutorial
Loops in Java allow you to execute a block of code repeatedly as long as a condition is true.
They help in reducing code repetition and performing iterative tasks efficiently.
1. Types of Loops in Java
- for loop
- while loop
- do-while loop
- enhanced for loop (for-each)
2. for Loop
- Executes a block a specific number of times
- Syntax:
Example – Print numbers 1 to 5:
Output:
Nested for Loop Example
- Used to iterate inside another loop
Output:
3. while Loop
- Repeats block while condition is true
- Syntax:
Example – Print numbers 1 to 5:
Output:
4. do-while Loop
- Executes block at least once, then checks condition
- Syntax:
Example – Print numbers 1 to 5:
Output:
5. Enhanced for Loop (for-each)
- Simplifies iteration over arrays or collections
- Syntax:
Example – Array iteration:
Output:
6. Infinite Loops
- Loop that never ends
- Can be intentional or accidental
Example – Infinite while loop:
- Use break to exit an infinite loop
7. Loop Control Statements
- break – Exits the loop immediately
- continue – Skips current iteration and moves to next
Example – break and continue:
Output:
8. Example Program – Looping Statements
Sample Output:
9. Summary
- Loops allow repetition of code
- Types: for, while, do-while, enhanced for
- Use nested loops for multidimensional iteration
- break and continue control loop flow
- Choose loop based on condition check requirement