For Loops: The Precise Counter

For Loops: The Precise Counter in Java: A coil winder lays copper wire onto a bobbin, and the number of turns is the whole specification of the part.

The Analogy: The Three Thumbwheels On The Coil Winder

A coil winder lays copper wire onto a bobbin, and the number of turns is the whole specification of the part. On the front of the machine is a brass plate with three thumbwheels: the turn to start counting from, the turn to stop at, and how far the counter moves on each click. All three sit side by side under the operator's hand, and you can read the entire job off that one plate without touching the machine.

The order the plate is obeyed in never varies. The start wheel is read once, when the job begins. The stop wheel is consulted before every single turn, including the first. The step wheel acts after each turn is finished. So a plate set to start at zero and stop at zero winds nothing at all, and there is no argument about it -- the machine checks before it moves. And the counter belongs to the plate, not to the workshop: when the job ends the wheels are reset and the number is gone. You cannot walk away with it.

There is a second way to run this machine, and it has no thumbwheels. When the job is "wind every bobbin on the rack", the loader does not count bobbins. He walks the rack from one end and stops when he runs out. He has given something up -- he cannot be told to fetch the fourth bobbin, because he is not keeping a position -- and in exchange he can never reach for a bobbin that is not there. That trade is exactly the enhanced for loop.

The failures are all failures of the plate, and they are quiet. A stop wheel set one past the last bobbin sends the arm into empty air, which is the off-by-one that ends in ArrayIndexOutOfBoundsException. An operator who reaches in and nudges the counter mid-run leaves the machine winding a part that matches no drawing. A step wheel set to zero means the counter never reaches the stop and the machine runs until somebody pulls the isolator. And if a colleague drops another bobbin onto the rack while the loader is halfway along it, the count the loader is working to no longer describes the rack he is standing in front of -- sometimes he notices and stops dead, and sometimes he simply finishes early and reports the job done.


Syntax or Core Structure

The three clauses are separated by semicolons and are read in the order initialise, test, advance. The enhanced form replaces all three with a colon.

public class Winder {
    public static void main(String[] args) {
        for (int turn = 1; turn <= 5; turn++) {
            System.out.println("winding  " + turn);
        }

        for (int turn = 0; turn > 0; turn++) {
            System.out.println("never    reached");
        }

        for (int turn = 10; turn >= 6; turn -= 2) {
            System.out.println("unwind   " + turn);
        }

        String[] bobbins = { "b-1", "b-2", "b-3" };
        for (String bobbin : bobbins) {
            System.out.println("loading  " + bobbin);
        }

        int total = 0;
        for (int i = 0, j = 10; i < j; i++, j--) {
            total++;
        }
        System.out.println("meetings " + total);
    }
}

Output:

winding  1
winding  2
winding  3
winding  4
winding  5
unwind   10
unwind   8
unwind   6
loading  b-1
loading  b-2
loading  b-3
meetings 5

The second loop prints nothing, because the test runs before the first pass and 0 > 0 is false. The third counts downwards -- turn++ is a convention, not a rule, and any expression that changes the variable will do. The last loop shows that the initialise and advance clauses may hold several comma-separated parts: two counters walking towards each other from 0 and 10 meet after five passes. What you may not do is declare two variables of different types in one initialiser; int i = 0, j = 10 is legal, int i = 0, long j = 10 is not.


Technical Depth: What The Three Clauses May Be, And What The Counter Is Worth Afterwards

All three clauses are optional

ClauseLeft empty meansTypical useWhat breaks
initialisenothing is set upthe counter already exists above the loopa stale value from a previous loop
testthe test is treated as truefor (;;) as a deliberate infinite loopnothing, if a break is reachable; a hang if not
advancenothing changes automaticallythe body advances conditionallyan infinite loop with no visible cause

for (;;) and while (true) compile to the same thing. Prefer while (true) for a genuinely unbounded loop, because an empty for header makes a reader hunt for the clauses that are not there.

The counter's scope, and its value on the way out

String[] parts = { "b-1", "b-2", "b-3", "b-4" };

int found = -1;
for (int i = 0; i < parts.length; i++) {
    if (parts[i].equals("b-3")) {
        found = i;
        break;
    }
}
System.out.println("found    " + found);

int scan = 0;
for (; scan < parts.length; scan++) {
    if (parts[scan].startsWith("z")) {
        break;
    }
}
System.out.println("scan     " + scan);
System.out.println("hit      " + (scan < parts.length));

Output:

found    2
scan     4
hit      false

A variable declared in the initialiser exists only inside the loop; referring to i after the closing brace does not compile. That is a feature, and it is why the first loop copies what it wants into found before breaking.

The second loop declares scan outside so the value survives, and that survival is a trap: after a loop that ran to completion scan equals parts.length, which is one past the last index and not a valid subscript. The only way to know whether scan is an index or a sentinel is the scan < parts.length test on the last line. If you keep a counter alive past its loop, keep that test with it.

The comparison operator is where off-by-one lives

int[] a = { 7, 8, 9 };

int strict = 0;
for (int i = 0; i < a.length; i++) {
    strict += a[i];
}
System.out.println("strict   " + strict);

boolean overran = false;
int loose = 0;
try {
    for (int i = 0; i <= a.length; i++) {
        loose += a[i];
    }
} catch (ArrayIndexOutOfBoundsException e) {
    overran = true;
}
System.out.println("summed   " + loose);
System.out.println("overran  " + overran);

Output:

strict   24
summed   24
overran  true

Valid indices run from 0 to length - 1, so the only correct bound for a zero-based counter is i < a.length. Note what the second loop did before it failed: it summed all three elements correctly and then threw. Half-finished work plus an exception is the normal shape of this bug, and it is why an off-by-one found in production has usually already written something.

The enhanced form, and the one thing you may not do inside it

FormIndex availableRemove while traversingWorks on arraysWorks on any Iterable
indexed foryesyes, if you step the index backyesonly via get(i)
enhanced fornonoyesyes
explicit Iteratornoyes, via remove()noyes

Over an array the enhanced form compiles to an indexed loop; over a collection it compiles to a call to iterator() and a hasNext/next pair. That hidden iterator is what makes structural modification illegal, and the way it fails is worse than an exception.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.List;

public class Rack {
    public static void main(String[] args) {
        List<String> rackA = new ArrayList<String>(Arrays.asList("b-1", "b-2", "b-3"));
        boolean threwA = false;
        try {
            for (String b : rackA) {
                if (b.equals("b-1")) {
                    rackA.remove(b);
                }
            }
        } catch (ConcurrentModificationException e) {
            threwA = true;
        }

        List<String> rackB = new ArrayList<String>(Arrays.asList("b-1", "b-2", "b-3"));
        boolean threwB = false;
        try {
            for (String b : rackB) {
                if (b.equals("b-2")) {
                    rackB.remove(b);
                }
            }
        } catch (ConcurrentModificationException e) {
            threwB = true;
        }

        List<String> rackC = new ArrayList<String>(Arrays.asList("b-1", "b-2", "b-3"));
        rackC.removeIf(b -> b.equals("b-2"));

        System.out.println("threw A  " + threwA);
        System.out.println("size A   " + rackA.size());
        System.out.println("threw B  " + threwB);
        System.out.println("size B   " + rackB.size());
        System.out.println("size C   " + rackC.size());
    }
}

Output:

threw A  true
size A   2
threw B  false
size B   2
size C   2

Two lists, the same code, one element removed from each, and only one of them complains. The iterator's hasNext() is nothing cleverer than "is my cursor different from the list's size". Removing the first of three leaves the cursor at 1 and the size at 2, so hasNext() says yes, next() checks the modification count and throws. Removing the second of three leaves the cursor at 2 and the size at 2, so hasNext() says no and the loop exits cleanly -- having never looked at b-3.

The second case is the dangerous one precisely because nothing went wrong on the surface. A filter written that way skips one element out of every list whose unwanted item happens to sit second from the end, and the tests that use a two-element list pass. Use removeIf, or an explicit Iterator with it.remove(), or build a new list; never remove inside an enhanced for.


Real World Example: A Depreciation Schedule That Has To Land Exactly On Zero

An asset is bought for a known price and written off over a known number of periods. Both numbers come from a contract, so the pass count is fixed before the first line runs -- this is a for loop, and nothing about it is negotiable. What is interesting is the last period.

import java.util.Locale;

public class Depreciation {

    private static final int COST_PENCE = 100000;
    private static final int TERM = 7;

    public static void main(String[] args) {
        int monthly = COST_PENCE / TERM;
        int naiveTotal = 0;
        int exactTotal = 0;
        int book = COST_PENCE;

        for (int month = 1; month <= TERM; month++) {
            int naive = monthly;
            int exact = (month == TERM) ? COST_PENCE - exactTotal : monthly;
            naiveTotal += naive;
            exactTotal += exact;
            book -= exact;
            System.out.println(String.format(Locale.ROOT,
                    "month %d  naive %5d  exact %5d  book %6d",
                    month, naive, exact, book));
        }

        System.out.println("cost       " + COST_PENCE);
        System.out.println("monthly    " + monthly);
        System.out.println("naive sum  " + naiveTotal);
        System.out.println("exact sum  " + exactTotal);
        System.out.println("residue    " + (COST_PENCE - naiveTotal));
        System.out.println("closing    " + book);
        System.out.println("balances   " + (exactTotal == COST_PENCE));
    }
}

Output:

month 1  naive 14285  exact 14285  book  85715
month 2  naive 14285  exact 14285  book  71430
month 3  naive 14285  exact 14285  book  57145
month 4  naive 14285  exact 14285  book  42860
month 5  naive 14285  exact 14285  book  28575
month 6  naive 14285  exact 14285  book  14290
month 7  naive 14285  exact 14290  book      0
cost       100000
monthly    14285
naive sum  99995
exact sum  100000
residue    5
closing    0
balances   true

The loop count here is a contract term, not something the program works out. Seven periods were agreed when the asset was capitalised, and no amount of inspecting the data during the run will change that number. That is the whole test for choosing for over while: can you write the pass count on the plate before you start? If yes, put it in the header where a reader can check it in one glance.

The residue is the point of the lesson. 100000 / 7 is 14285, integer division truncates, and seven charges of 14285 come to 99995 -- five pence of an asset that never leaves the balance sheet. The month == TERM ternary is the entire fix: every period but the last takes the standard charge, and the last takes whatever is left. That single last-iteration special case is how depreciation, VAT splits, instalment plans and stock allocations are all done, and it is why the for header alone is never the whole story. balances true on the final line is the assertion that makes the fix worth having, and it should be a real test, not a printed boolean.

Notice that this loop counts from 1 while every other loop in this lesson counts from 0, and that the difference is deliberate. A counter that indexes an array must start at 0 because that is where arrays start. A counter that is a domain value -- a month number, an instalment number, a page number -- should start where the domain starts, because then month == TERM reads as "the final month" and the printed figures need no adjustment. Count from 0 to subscript something; count from 1 when the number itself is the answer. Mixing the two is how you end up with month + 1 scattered through the output code and one place where somebody forgot it.

The honest limits. naive is computed and printed alongside exact every single month, which is a teaching device and would be a defect in real code: carrying a known-wrong figure next to the right one in the same row invites somebody downstream to read the wrong column. The model is also straight-line and nothing else -- there is no residual value, no mid-period acquisition, and no disposal, so an asset sold in month 4 leaves this schedule confidently claiming three more charges against something the company no longer owns. The real design flaw is the residue policy: dumping the entire rounding difference into the final period is defensible at five pence over seven months and indefensible over a 240-month term, where the accumulated drift lands as one visibly wrong last instalment; lenders spread it across the early periods instead, and this code has no way to express that. And int pence overflows a little past twenty-one million pounds, so this program can schedule a van and not a building.


Common Mistakes

  1. Writing i <= array.length. Valid indices stop at length - 1, so this walks one step past the end and throws ArrayIndexOutOfBoundsException -- after correctly processing everything else. The only right form for a zero-based counter is i < array.length.
  1. Modifying the counter inside the body. for (int i = 0; i < n; i++) { ... i++; ... } advances twice on some passes and once on others. If the body needs to skip an element, express that with a continue or a condition, not by reaching into the loop's own counter.
  1. Leaving the advance clause empty and forgetting to advance in the body. for (int i = 0; i < n;) is legal and reads as deliberate, which is exactly why nobody notices the missing i++ on one branch of an if. Keep the advance in the header where the header promises it is.
  1. Removing from a collection inside an enhanced for. Sometimes it throws ConcurrentModificationException and sometimes it silently skips the last element, and which one you get depends on the position of the item removed. Use removeIf, an explicit Iterator, or a new list.
  1. Keeping a hand-rolled counter alongside a for-each. int i = 0; for (String s : list) { ... i++; } looks harmless until someone adds a continue above the i++, at which point the counter and the position disagree and nothing reports it. If you need the index, use the indexed form.
  1. Reusing one counter across two loops. Declaring int i above both loops means the second starts from whatever the first left behind. Declare the counter in the initialiser so it dies with its loop and the compiler catches the reuse.
  1. Calling an expensive method in the condition. The condition runs on every pass, so for (int i = 0; i < recount(); i++) calls recount() n + 1 times. list.size() on an ArrayList is free and fine; anything that scans, queries or allocates belongs in a variable above the loop.
  1. Counting with float or double. for (double x = 0.0; x != 1.0; x += 0.1) never terminates, because ten additions of 0.1 do not produce exactly 1.0. Count passes with an int and divide.
  1. A stray semicolon after the header. for (int i = 0; i < 5; i++); is a complete loop with an empty body. The block underneath it then runs exactly once, with i already out of scope, and the compiler says nothing.

Best Practices

  • Use for when the pass count is knowable before the first pass, and while when it is not. The header exists so that a reader can audit initialise, test and advance without reading the body. Do not spend that on a loop whose end depends on what it discovers.
  • Prefer the enhanced form whenever the index is not part of the work. for (String b : bobbins) cannot go out of bounds and cannot be given the wrong bound, and those are two of the three bugs in this lesson.
  • Declare the counter in the initialiser. Scoping it to the loop makes accidental reuse a compile error instead of a wrong answer, and it stops anyone reading the counter after the loop as if it were the last valid index.
  • Count from 0 to subscript, from 1 when the number is the answer. Match the loop bounds to the domain when the counter is printed or compared against a term length; otherwise stay zero-based and use i < length.
  • Handle the last iteration explicitly when arithmetic must balance. A per-period figure derived by integer division will not sum to the total. Let the final period absorb the remainder and assert that it does.
  • Hoist anything invariant out of the condition and the body. The condition runs once per pass plus once more; the body runs once per pass. Neither is the place for a value that cannot change.
  • Use removeIf or an explicit Iterator to modify a collection you are traversing. The enhanced form has no legal way to do it, and its illegal way fails silently half the time.
  • Keep the header free of side effects. The three clauses should set up, test and advance the counter and do nothing else. A method call with consequences hidden in the advance clause is invisible to everyone reading the body.

Practice Exercises

  1. The Off-By-One Hunt. Take the strict/loose block and write three more variants of the same sum: i <= a.length - 1, i < a.length - 1, and a loop starting at i = 1. Predict each total on paper first, then run all five and print them in one column. Three of the five are wrong in three different ways; say for each one whether it throws, undercounts or overcounts, and which of the three a unit test on a three-element array would actually catch.
  1. The Twelve-Month Schedule. Change TERM to 12 and COST_PENCE to 250000. Work out monthly, naive sum and residue by hand before running it, then confirm. Now change the residue policy: instead of loading the whole difference onto the final month, add one extra penny to each of the first residue months. Print both schedules side by side and check that balances is still true for each.
  1. The Silent Removal. Build a four-element list and, in four separate runs, remove the element at each position in turn inside an enhanced for. Tabulate which positions throw ConcurrentModificationException, which exit silently, and what the final size is in each case. Then rewrite the whole thing with an explicit Iterator and it.remove() and show that all four positions now behave identically.