Java For Loop — i-- Termination Bug Kills Batch Jobs
CPU pinned at 100%? A for loop using i-- runs forever.
- A for loop repeats a block of code a known number of times using three parts: initializer, condition, update
- Arrays are zero-indexed — always use i < array.length, never i <= array.length
- break exits the loop entirely; continue skips only the current iteration
- Nested loops multiply — an outer loop of N and inner loop of M means N x M executions
- The #1 runtime crash is ArrayIndexOutOfBoundsException from off-by-one errors
- Biggest trap: a stray semicolon after the for header creates an empty loop body with no compile error
- The condition is checked one more time than the body executes — relevant when the condition has side effects
Imagine you have 30 birthday invitations to write. You would not invent a new process for each one — you would repeat the same action 30 times. A for loop is Java's way of saying 'do this exact thing a set number of times, then stop.' It is a built-in repeating machine. You tell it where to start, when to stop, and how to count — and it handles the rest.
Here is what makes it different from just copying code 30 times: the loop knows which repetition it is on. That built-in counter is what lets you say 'print invitation number 7' or 'grab the 12th score from this list.' The counter is not just a convenience — it is the thing that makes loops genuinely useful instead of just shorter.
Almost every real program needs to repeat something. A banking app applies interest to thousands of accounts. A game redraws the screen 60 times per second. A search engine scores millions of web pages.
The for loop solves this elegantly. It lets you write an action once and tell Java exactly how many times to run it. It also keeps a counter variable automatically, so you always know which repetition you are on.
By the end of this article you will understand every part of a for loop's syntax, be able to write one from scratch without looking anything up, know how to loop through arrays correctly, nest one loop inside another without blowing up your performance budget, and spot the mistakes that trip up nearly every beginner — including a few that produce no compile error at all, which makes them genuinely dangerous.
These are not academic exercises. Every example here reflects something you will write in real production code within your first few months of Java development.
Anatomy of a Java for Loop — What Each Part Actually Does
A for loop has three parts crammed into one line, separated by semicolons. Each part has a specific job, and understanding each job separately makes the whole thing click immediately.
The first part is the initializer. It runs exactly once — right before the loop starts. You use it to create and set your counter variable. Think of it as setting the odometer to zero before a road trip. It runs once, establishes your starting position, and then stays out of the way.
The second part is the condition. Java checks this before every single repetition, including the very first one. If it evaluates to true, the loop body runs. If it evaluates to false, the loop stops immediately and Java moves on to whatever comes after the closing brace. This is the gatekeeper — it controls entry, not exit.
The third part is the update. It runs after every repetition of the loop body — right before the condition is checked again. You use it to change your counter so that the loop eventually ends. If you get this wrong, you get an infinite loop. If you leave it out entirely, same result.
The execution order is fixed and worth memorizing: initializer runs once → condition checked → body runs if true → update runs → condition checked again → repeat. That cycle continues until the condition is false.
One detail that catches people off guard: the condition is checked one more time than the body executes. A loop that runs 10 times checks its condition 11 times — once for each successful iteration, and once more when it evaluates to false and the loop exits. This is normally invisible, but if your condition calls a method with side effects, that method runs 11 times, not 10.
- Initializer runs exactly once — before anything else, never again
- Condition is checked before every single iteration, including the first — if it starts false, the body never runs at all
- Body runs only if the condition is true — nothing inside the body executes if the gate is closed
- Update runs after every body execution, before the next condition check — this is your responsibility to get right
- The condition is evaluated one more time than the body executes — account for this if the condition has side effects like a method call
- If you can read the header as a plain English sentence and it makes sense, the loop is probably correct: 'start at 1; keep going while at or below 5; add 1 each round'
i < 10. It becomes a real issue when the condition calls a method: for (int i = 0; i < list.size(); i++) calls list.size() on every check. For an ArrayList that is a cheap O(1) call. For a database-backed collection or a method with side effects, that extra call has consequences.int size = list.size(); for (int i = 0; i < size; i++). This also eliminates the repeated method call overhead in tight loops.Looping Through an Array — The Most Common Real-World Use Case
The single most common use of a for loop in Java is walking through every element of an array. An array is a numbered list of values where every slot has an index. The critical detail — the one that causes more beginner crashes than anything else — is that Java arrays are zero-indexed. The first element lives at index 0, not index 1.
A 5-element array has indices 0, 1, 2, 3, and 4. The last valid index is always array.length - 1. There is no index 5 in a 5-element array. Ask for it and Java throws ArrayIndexOutOfBoundsException immediately at runtime with no warning beforehand.
This is precisely why the standard idiom for looping through an array is i < array.length with a strict less-than, not i <= array.length. With <=, when the counter reaches array.length (which is 5 for a 5-element array), the condition is still true, Java tries to read array[5], finds nothing there, and crashes.
The loop counter doubling as the array index is the elegant core of this pattern. You are not maintaining two separate things — the position in the array and the current iteration number are the same value. That is by design.
One practical note: if you only need the values and do not need the index for anything, the enhanced for-each loop (for (int score : testScores)) is cleaner. But the moment you need the position — to compare adjacent elements, to write back to the array, to display 'Score 3 of 5' — you need the indexed for loop.
i < array.length, never i <= array.length. With <=, on the final iteration i equals array.length — which is 5 for a 5-element array — and Java will throw ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5. The array ends at index 4. There is no index 5. The crash happens at runtime with no compile warning, which is exactly what makes this the number one array loop mistake for beginners.
Secondary trap: i < array.length - 1 is also wrong — it silently skips the last element with no error. Your output looks almost right, which makes this harder to spot than an outright crash.array.length is computed dynamically and can be zero. A loop with i < 0 never executes — that is fine. But code that assumes the array has at least one element after the loop exits will behave unexpectedly. Always validate that an array is non-empty before processing it if your downstream logic assumes it has content.Arrays.stream(testScores).sum() and IntStream operations replace accumulator loops for simple aggregations. They handle edge cases like empty arrays cleanly and are harder to get wrong. Use them when index tracking is not needed.length - 1. This is not a quirk — it is how every array and list in Java works, and internalizing it early saves significant debugging time.<= instead of < is the single most common for loop bug in Java. The fix is one character. The crash it prevents is an immediate runtime exception.Nested for Loops — Loops Inside Loops (And When You Actually Need Them)
Sometimes one dimension of repetition is not enough. Printing a multiplication table requires every number from 1 to 10 multiplied by every other number from 1 to 10. Processing a 2D grid of pixels requires visiting every row and every column. Comparing every element in a list against every other element requires two passes through the data. These are inherently two-dimensional problems, and nested loops are how Java handles two dimensions.
A nested loop is a loop inside another loop. The outer loop controls one dimension — typically rows. The inner loop controls the other — typically columns. For every single iteration of the outer loop, the inner loop runs its full cycle from start to finish. If the outer loop runs 5 times and the inner loop runs 5 times, the body executes 25 times.
That multiplication is the key insight and the key danger. Two loops with bounds of 1000 each produce one million iterations. At one microsecond per iteration — a reasonable estimate for simple arithmetic — that is one second. Add a database call inside the inner loop at 10ms each and you are at 2.7 hours. Nested loops with large bounds and non-trivial inner bodies are a reliable path to production timeouts.
Before writing a nested loop, always calculate the total iterations explicitly. If N × M is larger than your data set comfortably allows within your latency budget, you need a different algorithm — often a HashMap or Set that turns an O(N²) comparison into O(N).
Variable naming in nested loops is not a style preference — it is a correctness requirement. Using i for both loops means the inner loop's i shadows the outer loop's i. The outer counter stops updating correctly and the output is wrong in a way that is genuinely confusing to debug. Use i and j, or better, use descriptive names like row and col that make the two-dimensional intent clear.
- Outer loop runs N times — for each of those N runs, the inner loop completes its entire M-cycle before the outer counter increments
- Total executions = N × M — this multiplicative growth is the core characteristic and the core risk
- Always use different variable names —
rowandcol, oriandj. Reusing the same name causes the inner loop to shadow the outer counter, breaking both loops silently - Three nested loops produce N × M × P executions — the exponent grows fast. Three loops at 100 each is one million iterations
- If you can solve the problem with a single loop plus a data structure like a HashMap, that is almost always the right call for production code
- Break inside the inner loop only exits the inner loop — the outer loop continues. Plan your exit strategy before you write the nesting.
Controlling Loop Flow with break and continue
Sometimes you need to exit a loop before it naturally finishes, or skip one specific iteration without stopping the whole loop. Java provides two keywords for exactly these situations: break and continue.
break is the emergency exit. The moment Java encounters break, it leaves the current loop entirely — no more iterations, no revisiting the condition, no cleanup. Execution continues with the first line after the loop's closing brace. This is the right tool when you are searching for something and have found it. Checking the remaining elements would be wasted work.
continue is more nuanced. It does not stop the loop — it abandons only the current iteration and jumps immediately to the update step, then rechecks the condition. The loop continues normally from the next iteration. Think of it as 'never mind this one, move on.' This is useful when most elements need processing but a specific subset should be skipped — blank entries, null values, filtered-out categories.
The failure mode when you confuse them is silent: your code runs without error but produces wrong results. break when you meant continue terminates the loop too early, silently skipping every remaining element. continue when you meant break keeps processing elements you should have stopped at, potentially corrupting state or producing extra output. Neither produces a compile error or exception. The bug hides in the output.
One important scoping rule: both keywords only affect the loop they are directly inside. In a nested loop, break in the inner loop exits the inner loop and returns control to the outer loop — the outer loop continues. To exit the outer loop from inside the inner loop, use a boolean flag checked in the outer loop's condition, or use a labeled break if your team accepts that style.
break ends the loop entirely — no more iterations, period. continue ends only the current iteration — the loop carries on with the next one.
If you mix them up, your program will not crash. It will silently produce wrong results, which is significantly harder to debug than an exception. Before writing either keyword, ask yourself one question out loud: 'Do I want to stop everything right now, or do I just want to skip this one item and keep going?' The answer tells you which keyword to use.break outerLabel;) is valid Java and does the same thing in fewer lines, but it tends to generate discussion in code reviews. The flag pattern communicates intent more clearly to the next engineer reading the code.Infinite Loop Takes Down Batch Processing Service
for (int i = 0; i < array.length; i--) — the counter moved away from the stopping condition on every iteration, guaranteeing it would never reach a state where i < array.length became false. The compiler did not flag this because it is syntactically valid Java. The code review did not catch it because the diff looked like a one-character change.i-- with a corrected starting position of array.length - 1 and an updated condition of i >= 0. Added a loop iteration counter with a hard upper bound (maxIterations = array.length * 2) as a safety net that logs a fatal error and breaks if exceeded. Added structured logging every 1000 iterations so stalled loops become visible in the observability stack within minutes rather than hours.- Always verify the update operator moves the counter toward making the condition false — read the header as a sentence and confirm it terminates
- Infinite loops are syntactically valid Java — the compiler has no way to catch them, and neither do most static analysis tools
- Add iteration guards (maxIterations) in production batch jobs as an explicit safety net; treat them as circuit breakers, not crutches
- Log loop progress periodically in long-running jobs — silent loops are invisible loops, and invisible loops become incidents
- Code review a loop refactor as carefully as a new loop — the diff being small does not mean the risk is small
Key takeaways
array.length - 1. Always start your loop counter at 0 and use i < array.length as your condition<=. This single character difference is the most common source of ArrayIndexOutOfBoundsException in beginner Java code.break exits the entire loop immediatelycontinue exits only the current iteration and moves to the next one. Confusing them produces silent logic bugs, not compile errors. In nested loops, both keywords only affect the innermost loop they appear in.for (int i = 0; i < 10; i++); creates an infinite empty loop over nothing, then runs the following block once. No compile error, no exception — just silently wrong behavior.Common mistakes to avoid
5 patternsUsing i <= array.length instead of i < array.length
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5. The application terminates immediately on the iteration where i equals array.length.i < array.length as your condition. The strict less-than stops the counter at 4, which is the last valid position. Change <= to < and the crash disappears. Also watch for the opposite mistake: i < array.length - 1 silently skips the last element with no error, which is harder to notice than a crash.Accidentally creating an infinite loop with the wrong update operator
i++. Counting downward toward a minimum: use i--. Read the header as a sentence: 'start at 0, keep going while less than 10, subtract 1 each time' — that sentence describes an infinite loop and should sound wrong. In production batch jobs, add a maxIterations guard that logs a fatal error and breaks if the expected iteration count is exceeded.Putting a semicolon immediately after the for loop header
for (...). The opening curly brace { should follow immediately. If your editor's auto-formatter inserts a newline between the header and the brace, that is fine — the semicolon is the problem, not the whitespace.Reusing the same counter variable name in nested loops
i and j, or better, descriptive names like row and col that communicate the two-dimensional intent. When the inner loop declares its own int i, it shadows the outer i for the duration of the inner loop's execution. The outer counter stops advancing correctly. Use distinct names always — this is not a style preference, it is a correctness requirement.Confusing break and continue in loops with multiple conditions
break. If the answer is skip this one and keep going, use continue. In code review, always explain which behavior you intend in a comment adjacent to the keyword — it eliminates ambiguity for anyone reading the code later.Interview Questions on This Topic
What are the three parts of a Java for loop header, and in what order does Java execute them? Can any of the three parts be left empty, and if so what happens?
for (;;) with all three parts empty is a deliberate infinite loop idiom sometimes used for server event loops with internal break conditions.Frequently Asked Questions
That's Control Flow. Mark it forged?
6 min read · try the examples if you haven't