A loop corresponding to the following code should return 10:
int x = 0; for (int i = 0; i < 5; ++i) { x += i; } return x;
However, the loop assembled as follows returns 15:
MethodHandle iter = MethodHandles.constant(int.class, 5);
MethodHandle init = MethodHandles.constant(int.class, 0);
MethodHandle body = ...; // handle to a method int m(int c, int x) { return x + c; }
MethodHandle loop = MethodHandles.countedLoop(iter, init, body);
assertEquals(10, loop.invoke());
The reason for this is that the MHs.countedLoop/3 combinator indeed initialises the loop counter to 0, but increments it right away before the first invocation of the body handle. This should be fixable by reordering clauses, or by initialising the counter to -1.