| Part | When it runs | Typical example | What it does |
|---|---|---|---|
| Initialization | Once, before anything else | int i = 0 | Declares or sets the loop counter |
| Condition | Before every pass | i < 5 | true runs the body; false ends the loop |
| Update | After every pass | i++ | Moves the counter toward the end |
Rules worth remembering:
- The two semicolons inside the parentheses are always required, even when a part is empty.
- The condition must be of type
boolean(orBoolean). Java does not treat0as false the way C does. - All three parts are optional. A missing condition counts as
true.
How Does a For Loop Work in Java?
A for loop always follows this order: initialization (once), then condition, body, update, condition, body, update, and so on, until the condition is false.
The loop back from Update to the condition is what makes the loop repeat. The only way out is the condition becoming false, or a break, return, or exception inside the body.
For Loop Examples in Java
Example 1: Print a Message Five Times
Code (Java 21):
Output:
Lap 1 completedLap 2 completed
Lap 3 completed
Lap 4 completed
Lap 5 completed
Race finished
lap starts at 1. The body runs while lap <= 5, and lap++ adds 1 after each pass.
Dry Run of Example 1
| Step | lap | lap <= 5 | Action |
|---|---|---|---|
| Init | 1 | — | lap is created with value 1 |
| Pass 1 | 1 | true | prints “Lap 1 completed”, then lap becomes 2 |
| Pass 2 | 2 | true | prints “Lap 2 completed”, then lap becomes 3 |
| Pass 3 | 3 | true | prints “Lap 3 completed”, then lap becomes 4 |
| Pass 4 | 4 | true | prints “Lap 4 completed”, then lap becomes 5 |
| Pass 5 | 5 | true | prints “Lap 5 completed”, then lap becomes 6 |
| Check | 6 | false | loop ends; “Race finished” is printed |
The condition was checked 6 times but the body ran 5 times. The last check is always the one that fails.
Can a For Loop Run Zero Times in Java?
Yes. The condition is checked before the first pass, so if it starts out false, the body never runs.
Code (Java 21):
Output:
No more tasksThat makes the for loop safe for empty input: an empty array or a count of zero simply skips the body.
Example 2: Loop Through an Array (Total and Average)
Java arrays are zero-indexed. An array with length elements has valid indexes from 0 to length - 1.
Code (Java 21):
Output:
Subject 1: 72
Subject 2: 85
Subject 3: 90
Subject 4: 64
Total = 311Average = 77.75
i < marks.length stops at index 3, the last valid index. The (double) cast prevents integer division, which would give 77 instead of 77.75.
Example 3: Reverse For Loop in Java (Countdown)
To count down, start high, flip the condition, and decrement.
Code (Java 21):
Output:
5 4 3 2 1 Liftoff!The same pattern goes through an array backwards: for (int i = arr.length - 1; i >= 0; i--).
Example 4: Custom Steps (Counting by 2 or Multiplying by 10)
The update can be any statement that moves the counter, not just ++.
Code (Java 21):
Output:
2 4 6 8 10 1 10 100 1000n += 2 is shorthand for n = n + 2. The update runs on every pass, so keep it cheap; don’t put slow method calls there.
Variations and Special Cases
For Loop With Multiple Variables in Java
The initialization and update parts can each contain several comma-separated items. The condition is still a single boolean expression; combine checks with && or ||.
A classic use is two indexes moving toward each other, here to check whether a word is a palindrome:
Code (Java 21):
Output:
racecar is a palindrome: trueThe type rule, stated precisely:
- If you declare variables in the header, they all share one type:
int left = 0, right = 6is fine, butint i = 0, double rate = 0.5does not compile. - If you only assign variables that were declared earlier, they can be different types:
Code (Java 21):
Output:
Year 1: 1000.00Year 2: 1100.00
Year 3: 1210.00
If a header needs three or more interacting counters, move some of the logic into the body. Readability matters more than fitting everything on one line.
Scope of the Loop Variable in Java
A variable declared in the initialization exists only inside the loop: the header and the body.
Code (Java 21, does not compile on purpose):
Compiler output:
ScopeError.java:6: error: cannot find symbolSystem.out.println(step);
^
symbol: variable step
location: class ScopeError
1 error
This is a feature: the counter can’t leak into the rest of the method. If you need the value after the loop, declare the variable before it:
Code (Java 21):
Output:
Body runs with k = 0Body runs with k = 1
Body runs with k = 2
After the loop, k = 3
After the loop, k is 3, not 2. The update ran once more and produced the value that failed the condition.
A practical use of this is searching an array and remembering where you stopped:
Code (Java 21):
Output:
First freezing day: day 3break exits the loop immediately. You’ll study break and continue in detail in Break and Continue in Java.
Nested For Loop in Java
A for loop inside another for loop is a nested loop. The inner loop finishes all its passes for each pass of the outer loop.
Code (Java 21):
Output:
1 2 3 42 4 6 8
3 6 9 12
The body of the inner loop runs 3 × 4 = 12 times. In general, nested loops over n items each run n × n times, written as O(n²).
Infinite For Loop in Java
Leaving out all three parts, for (;;), creates a loop with no condition, which Java treats as always true. You need break, return, or an exception to leave it.
Code (Java 21):
Output:
Value 128 reached after 7 doublingsfor (;;) and while (true) behave the same. Most Java developers find while (true) easier to read for deliberate endless loops. An accidental infinite loop usually comes from an update that moves the counter the wrong way, such as for (int i = 0; i < 10; i--).
A Quick Look Ahead: The For-Each Loop
Java also has an enhanced for loop (for-each) for reading every element when you don’t need the index:
Code (Java 21):
Output:
DelhiPune
Chennai
Use the classic for loop when you need the index, a reverse order, a custom step, or to compare neighbouring elements. Use for-each for simple read-only traversal. You’ll meet it again in the Arrays lessons.
For Loop vs While Loop vs Do-While Loop in Java
Any for loop can be rewritten as a while loop. The parts just move to different lines:
Code (Java 21):
Output:
Lap 1Lap 2
Lap 3
| Feature | for loop | while loop | do-while loop |
|---|---|---|---|
| Condition checked | Before each pass | Before each pass | After each pass |
| Minimum runs | 0 | 0 | 1 |
| Best when | The count or range is known | You loop until something changes | The body must run at least once (menus, input prompts) |
| Counter scope | Can be limited to the loop | Declared outside the loop | Declared outside the loop |
| Typical example | Go through an array | Read input until “quit” | Show a menu, then ask again |
Learn the other two next: While Loop in Java and Do-While Loop in Java.
Common Mistakes With For Loops in Java
Mistake 1: Using <= With array.length (Off-by-One)
Wrong:
Output (Java 21):
1020
30
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at OutOfBounds.main(OutOfBounds.java:5)
Why it happens: length is 3, so the last valid index is 2. <= lets i reach 3.
Fix: for (int i = 0; i < scores.length; i++). Rule of thumb: use < with a count or length, and <= only with an inclusive last value, such as 1 <= i <= 10.
Mistake 2: Starting at the Wrong Index
Starting at i = 1 on an array silently skips the first element. For {72, 85, 90, 64} it would total 239 instead of 311, and no error tells you. Start at 0 unless you deliberately need index 1, for example when comparing each element with the one before it.
Mistake 3: A Stray Semicolon After the Header
Wrong:
Output (Java 21):
Hello 3Why it happens: the ; is an empty loop body. The loop spins three times doing nothing, then the { } block runs once. (If i were declared in the header, this wouldn’t even compile, because i would be out of scope in the block.)
Fix: remove the semicolon after ).
Mistake 4: Using an int as the Condition
Wrong:
Compiler output (Java 21):
IntCondition.java:3: error: incompatible types: int cannot be converted to booleanfor (int n = 3; n; n--) {
^
1 error
Fix: write a real comparison: for (int n = 3; n > 0; n--).
Mistake 5: An Update That Isn’t a Statement
Wrong:
Compiler output (Java 21):
BadUpdate.java:3: error: not a statementfor (int i = 0; i < 3; i + 1) {
^
1 error
Why it happens: i + 1 computes a value but changes nothing, and Java rejects it. Fix: use i++, i += 1, or i = i + 1.
Mistake 6: Using a double Counter With !=
Wrong:
When run with a safety break after 15 passes, it prints (Java 21):
Still running after 15 steps, x = 1.5000000000000002Why it happens: 0.1 can’t be stored exactly in binary, so x never equals exactly 1.0; it skips past it.
Fix: count with an int (for (int tenths = 0; tenths < 10; tenths++)) and calculate tenths / 10.0 inside the body. If you must use a double, compare with <, not !=.
Mistake 7: Changing the Counter Inside the Body
Changing i inside the body (for example, i = 0 to “restart”) makes the loop hard to follow and easy to make infinite. Let the update section be the only place that moves the counter.
Best Practices
- Prefer
i < array.lengthfor array traversal. - Declare the counter in the header unless you need it after the loop.
- Use meaningful names (
row,col,day) when they help;i,j,kare fine for plain indexes. - Make sure every update moves the counter toward a
falsecondition. - Keep the header simple; put complex logic in the body or a helper method.
- Count with integers, not
double. - Always use braces
{ }, even for a one-line body. This prevents bugs when someone adds a second line later. - Use for-each when you only read elements and don’t need the index.
Real-World Example: Class Result Report
This mini-program combines everything above: array traversal, a running total, counting, and tracking the maximum.
Code (Java 21):
Output:
Asha: 78 (PASS)Ravi: 35 (FAIL)
Meena: 92 (PASS)
Karan: 56 (PASS)
Divya: 41 (PASS)
Passed: 4 of 5
Class average: 60.4
Topper: Meena with 92
The two arrays share the same index i. That is exactly the case where a classic for loop beats for-each.
Other places you’ll see for loops: processing each row of a report, generating invoice numbers, retrying an operation a fixed number of times, drawing grid-based games, and most array algorithms in DSA (sum, max, search, two pointers).
Practice Problems
- Easy: Print the multiplication table of 9 from 9 × 1 to 9 × 10. Hint: one loop from 1 to 10.
- Easy: Find the sum of all odd numbers from 1 to 99. Hint: start at 1 and use
i += 2. (Answer to check against: 2500.) - Easy–Medium: Print an array in reverse order. Hint: start at
length - 1and stop ati >= 0. - Medium: Count how many vowels a String has. Hint:
word.charAt(i)andi < word.length(). - Medium: Print a right-angled triangle of
*with 5 rows. Hint: a nested loop where the inner limit is the current row number.
Run your solutions in the ExamAdda online compiler.
Interview Questions on For Loop in Java
1. What are the three parts of a for loop, and when does each run?
Initialization runs once, at the start. The condition runs before every pass. The update runs after every pass, just before the next condition check.
2. Is the for loop entry-controlled or exit-controlled?
Entry-controlled. The condition is checked first, so the body can run zero times. Only do-while is exit-controlled.
3. How many times does for (int i = 0; i < 5; i++) check its condition?
Six times: five checks are true (for i = 0 to 4) and one is false (i = 5). The body runs five times.
4. Is there a difference between i++ and ++i in the update section?
No. The value of the update expression is thrown away, so both simply add 1. The difference only matters when the result is used, as in x = i++.
5. Can you declare two variables of different types in the initialization?
Not in a declaration: int i = 0, double d = 0 fails. You can assign previously declared variables of different types: i = 0, d = 0.0.
6. What does for (;;) do?
It is an infinite loop. A missing condition is treated as true. Exit it with break, return, or an exception.
7. Can you use the loop variable after the loop?
Not if it was declared in the header; its scope ends with the loop and you’ll get “cannot find symbol”. Declare it before the loop to keep its final value.
8. When would you choose a for loop over for-each?
When you need the index, reverse traversal, a custom step, parallel arrays, or to compare neighbouring elements.
Article Summary
- A for loop puts initialization, condition, and update in one header; initialization runs once, the condition before each pass, the update after each pass.
- It is entry-controlled, so the body may run zero times.
- Traverse arrays with
i = 0; i < array.length; i++;<=causesArrayIndexOutOfBoundsException. - Header-declared variables are local to the loop; declare outside to keep the final value.
- The condition must be
boolean; all three parts are optional, andfor (;;)loops forever until abreakorreturn. - Avoid stray semicolons,
doublecounters with!=, and changing the counter inside the body.
Conclusion
The for loop is the right tool when the number of repetitions, or the range to scan, is known before the loop starts. Once you can predict exactly how many times the condition is checked and what the counter holds when the loop exits, you can avoid nearly all off-by-one bugs. Next, see how Java handles loops whose end is not known in advance in the While Loop in Java lesson, then test yourself with ExamAdda practice questions.
Previous lesson: Naming Conventions in Java
Next lesson: While Loop in Java
References
- Oracle Java Tutorials: The for Statement
- Java Language Specification (Java SE 21), Chapter 14: The for Statement
Last updated: October 30, 2026. All examples tested on OpenJDK 21.
4. Series links
| Link | URL | Status |
|---|---|---|
| Previous: Naming Conventions | https://tech.examadda.org/java/naming-conventions | Verified (link on your page) |
| Next: While Loop | https://tech.examadda.org/java/while-loop | Verified (opened; its Previous link points back to this lesson) |
| Do-While Loop | https://tech.examadda.org/java/do-while-loop | Verified (sidebar) |
| Break & Continue | https://tech.examadda.org/java/break-and-continue | Verified (sidebar) |
| If-Else Statements (prerequisite) | https://tech.examadda.org/java/if-else-statements | Verified (sidebar) |
| Compiler / Practice (call to action) | /compiler, /practice | Verified (site navigation) |
| Labeled Statement | https://tech.examadda.org/java/labeled-statement | Verified, not used (nested-loop break is out of scope for this lesson) |
| Java Operators lesson | not found | Suggestion: add once the URL exists |
| Arrays / for-each lesson | Sidebar has an Array section, no URLs visible | Suggestion: link from the for-each preview |
Series order issue: the sidebar lists For Loop before If-Else and Switch, and the previous lesson is Naming Conventions. Loops depend on boolean conditions, so consider moving If-Else and Switch ahead of the loop lessons.
5. Change log
Errors fixed
- Wrong claim about the update section. The old text said
i + 1, j - 1“updates neither”. In fact it doesn’t compile (“not a statement”). The corrected rule and the compiler message are now shown. - Incomplete “same type” rule. The rule only applies to declarations; assigning variables of mixed types in the header is legal. Added a tested example.
- Two different “last updated” dates on the page (Sep 24 and Oct 29, 2026). Show only one.
- Code not visible in the page text. The code listings and diagrams don’t show up in the fetched page text, possibly because they render only in the browser. The new article includes every code example and its output as text.
Taken from the reference (AlgoMaster). The reference has about 30 points: 25 were already covered in your lesson (with nearly identical examples), 5 were expanded, 0 were new, and 0 were excluded. The expanded points are:
- exits from an infinite loop (
break,return, or an exception) - the type rule in the initialization
- the rule that the update must be a statement
- why the final counter value is the first one that fails the check
- keeping the update section cheap
All the reused examples were rewritten as new ones.
Added from competitor research: Mermaid flowchart, dry-run table, nested loops, for-each preview, for vs while vs do-while comparison with equivalent code, the rule that the condition must be boolean, the stray-semicolon trap, the double counter trap, changing the counter in the body, a real-world mini-program, 5 practice problems, and 8 interview questions.
Restructured: the opening now defines the loop in the first 60 words, a Key Takeaways box was added, and long-tail search questions became headings. “Quick Revision Summary” was renamed “Article Summary”.
Removed: nothing correct was removed. Only the examples that closely matched the reference were replaced.
Code testing: 21 programs were compiled and run with javac/java on OpenJDK 21.0.12. Every output, error message, and exception above is copied from the real runs.
6. Image plan
- Flowchart (the Mermaid diagram rendered as an SVG) under “How Does a For Loop Work”. Alt text: “Flowchart of a for loop in Java: initialization, condition check, body, update, exit”.
- Array index diagram for Mistake 1, showing boxes at indexes 0–2 and index 3 marked out of bounds. Alt text: “Array of length 3 with valid indexes 0 to 2; index 3 causes ArrayIndexOutOfBoundsException”.
- Nested loop grid (optional): a 3×4 grid highlighting the order of passes. Alt text: “Nested for loop running the inner loop 4 times for each of 3 outer passes”.