How to Use For Loop in Java: Syntax and Examples
In Java, a
for loop repeats a block of code a set number of times using three parts: initialization, condition, and update. The loop runs while the condition is true, updating the variable each time.Syntax
The for loop has three parts inside parentheses separated by semicolons:
- Initialization: sets the starting value of the loop variable.
- Condition: checked before each loop; if true, the loop runs.
- Update: changes the loop variable after each iteration.
The loop body contains the code to repeat.
java
for (initialization; condition; update) { // code to repeat }
Example
This example prints numbers from 1 to 5 using a for loop. It shows how the loop variable starts at 1, checks if it is less than or equal to 5, and increases by 1 each time.
java
public class ForLoopExample { public static void main(String[] args) { for (int i = 1; i <= 5; i++) { System.out.println(i); } } }
Output
1
2
3
4
5
Common Pitfalls
Common mistakes when using for loops include:
- Forgetting to update the loop variable, causing an infinite loop.
- Using the wrong condition, so the loop never runs or runs too many times.
- Declaring the loop variable outside the loop and accidentally reusing it.
Always check your loop's start, end, and update carefully.
java
/* Wrong: Infinite loop because i is never updated */ for (int i = 0; i < 5;) { System.out.println(i); } /* Correct: Update i in the loop */ for (int i = 0; i < 5; i++) { System.out.println(i); }
Quick Reference
| Part | Description | Example |
|---|---|---|
| Initialization | Set starting value | int i = 0 |
| Condition | Loop runs while true | i < 10 |
| Update | Change variable each loop | i++ |
| Loop Body | Code to repeat | System.out.println(i); |
Key Takeaways
A for loop repeats code using initialization, condition, and update parts.
The loop runs while the condition is true and updates the variable each time.
Always update the loop variable to avoid infinite loops.
Use clear start and end conditions to control how many times the loop runs.
Declare the loop variable inside the for statement for better scope control.