Java For Loop — i-- Termination Bug Kills Batch Jobs
CPU pinned at 100%? A for loop using i-- runs forever.
20+ years shipping production Java in banking & fintech. Everything here is grounded in real deployments.
- 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.
What a Java For Loop Actually Guarantees (and Doesn't)
A Java for loop is a control structure that repeats a block of code based on a boolean condition evaluated before each iteration. Its syntax — for (initialization; termination; increment) — bundles three operations: a one-time setup, a pre-iteration check, and a post-iteration step. The loop terminates when the termination expression evaluates to false. This is not syntactic sugar for a while loop; the increment clause executes after the body, not before, which matters when the increment itself has side effects.
The termination condition is checked at the top of each iteration. If it's false initially, the body never runs — zero iterations. The increment expression (e.g., i++ or i--) runs after the body completes, then control returns to the condition. This ordering is fixed: body, then increment, then condition. A common mistake is assuming i-- in the increment clause decrements before the condition check — it doesn't. That misunderstanding causes off-by-one errors and infinite loops in production batch jobs.
Use a for loop when the number of iterations is known or bounded, and you need a clear, self-contained iteration contract. It's the right choice for iterating over arrays, lists, or any range where the loop variable's lifecycle is local to the loop. In high-throughput systems, the for loop's predictable overhead (O(n) iterations, constant per-iteration cost) makes it suitable for tight loops processing thousands of records per second — provided the termination condition is rock-solid.
for (int i = n; i > 0; i--) but the body modified i under certain conditions, causing the loop to skip the termination check and run indefinitely.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.The Enhanced For-Each — When Your Loop Variable Is a Liability
You've been writing for (int i = 0; i < like it's 2004. Stop. Java's enhanced for-each loop eliminates index arithmetic, off-by-one errors, and the useless boilerplate of manually incrementing a counter.list.size(); i++)
The syntax is dead simple: for (ElementType variable : collection). The JVM handles the iteration mechanics. You don't touch the index. You don't call get(i). You just work with each element directly.
This isn't about syntactic sugar. It's about eliminating an entire class of bugs. Every time you write list.get(i), you're trusting that i stays within bounds. Every time you write i++, you're introducing a mutation that could be corrupted by a continue or a break. The for-each abstracts that risk away.
But here's the catch: you can't modify the underlying collection during iteration — you'll get a ConcurrentModificationException. And you can't access the index. For those cases, stick with the classic for loop. But for everything else, use for-each. Your code reviewer will thank you.
Iterator.remove() or collect items to remove in a separate list first. Your production logs will thank you.Labeled Loops — The Escape Hatch for Nested Chaos
Nested loops are a necessary evil. You iterate over customers, then over their orders, then over line items. Three levels deep. Then you find what you need and want to break out of all three loops at once.
A plain break only escapes the innermost loop. You'd end up with a boolean flag, an if check after every inner loop, and code that looks like a flowchart exploded. Labeled loops fix this.
Here's how it works: you slap a label before the outermost loop — search: for example — and then write break search; when you want to bail out entirely. Same goes for continue search;, which skips to the next iteration of the labeled loop.
Most developers don't know this exists. Some will argue it's 'goto in disguise'. They're wrong. It's a targeted, readable way to control flow in deeply nested structures. Use it sparingly — if you need more than one labeled loop in a method, refactor. But for that one case where you're three loops deep and the data matches, it's the cleanest hammer in the toolbox.
continue outerLabel; to skip the rest of an outer loop's iteration from a nested loop. Great for skipping an entire customer when their order has a blocked status — no extra flags needed.The Infinite Loop — When It's a Bug vs. When It's a Feature
The classic for (;;) is the compressed version of an infinite loop. Every developer writes one accidentally at least once — usually because they forgot the update statement. But infinite loops aren't always bugs. They're a deliberate pattern for daemon threads, event listeners, and connection pools that need to run until the application shuts down.
When you write a deliberate infinite loop, you MUST include an explicit exit condition. A break on a flag, a caught interrupt, or a timeout. Otherwise, your loop is a resource leak waiting to happen. The JVM won't save you — it will happily burn CPU cycles until you kill the process.
The three parts of the for loop are all optional. Omit them all, and you get for (;;). Omit just the condition, and it's still infinite — the JVM treats an empty condition as true. Same effect, slightly less obvious. Be explicit with while (true) if you want clarity, but for (;;) is idiomatic and just as readable to anyone who's been doing this more than a year.
Real-world usage: a message listener polling a queue. Start it in a thread, loop forever, process messages, and exit only when someone sets a volatile running flag to false. Your shutdown hook sets the flag, the loop breaks, the thread joins gracefully. No System.exit(), no hanging threads, no cleanup failures.
break inside an if inside a for (;;) is your only way out. Forget it, and you've got a CPU-screaming zombie thread. Always pair an infinite loop with a controllable exit condition — never assume the JVM will be killed.for (;;) for deliberate infinite loops in daemon threads. Always pair with a volatile flag or interrupt check. Never trust the JVM to save you from runaway loops.Traversing an Array? Your Loop Order Controls Performance
Arrays in Java are laid out sequentially in memory. That’s not trivia — that’s your cache coherency bonus. When you traverse from index 0 to length-1, you hit sequential memory addresses. The CPU prefetches the next few cache lines automatically. Your loop runs at memory speed, not CPU speed.
Reverse traversal? Same benefit — the hardware doesn’t care about direction. What kills you is striding: jumping by 2, 5, or accessing columns in a 2D array row-by-row but reading column-by-column. That skips cache lines and forces DRAM fetches. Your loop goes from nanoseconds to hundreds of nanoseconds per access.
If you’re processing an int[1000000], simple forward iteration is optimal. Don’t overthink it. The JVM’s JIT compiler also unrolls small fixed-size arrays. Write clear sequential loops. Let the hardware and JIT do the rest.
Collections Are Not Arrays — For-Each Hides the Iterator, Not the Cost
When you write for (String s : list) on an ArrayList, you get a linear pass. Fast. Same loop on a LinkedList? Your code looks identical, but your performance is abysmal. The for-each uses the collection’s iterator. ArrayList’s iterator jumps by index — O(1) per step. LinkedList’s iterator walks a node chain — O(1) per step, but the cache misses hurt. More importantly, you cannot modify the collection inside a for-each without a ConcurrentModificationException.
If you need to remove items mid-loop, use an explicit Iterator with Iterator.remove(). If you need index-based access on a List, use a traditional for loop with get(). That’s O(1) on ArrayList but O(n) on LinkedList — so pick your data structure first.
For HashMap, never iterate over entrySet() and call get(key) inside the loop. You’re doing double work. Use for (Map.Entry<K,V> entry : map.entrySet()) — one pass, one lookup.
Iterable.forEach() — The Internal Iterator That Breaks Your Control
Java 8 added a default method to Iterable: forEach(). It takes a Consumer lambda and iterates internally. The WHY: you trade loop control for cleaner code when you only need to apply an operation to each element. Unlike a for-each loop, forEach() cannot use break, continue, or return to exit early — the lambda runs to completion on every element. This becomes a production trap when you assume you can short-circuit; the compiler won't stop you, but your logic will silently process the entire collection. Use forEach() when you must unconditionally process every element and want a purely functional style. For conditional iteration, stick with the explicit for loop.
The Hidden Cost of forEach on Parallel Streams — Not All Iteration Is Sequential
Collection.forEach() always runs sequentially on the calling thread. But the default method is inherited by streams, and Stream.forEach() does NOT guarantee encounter order when run on a parallel stream. The WHY: parallel processing splits the stream into substreams; forEach processes results as they arrive, not in original order. If you need ordered processing under parallelism, use forEachOrdered(). A common performance pitfall: developers call parallelStream().forEach() expecting order, then add synchronization to fix nondeterministic output — which kills parallel speed. For ordered parallel iteration, prefer forEachOrdered() or stick to sequential for-each. For unordered operations, forEach() on parallel streams gives maximum throughput.
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
20+ years shipping production Java in banking & fintech. Everything here is grounded in real deployments.
That's Control Flow. Mark it forged?
13 min read · try the examples if you haven't