I wrote the following class:
public class TestOne {
public static void main(String[] args) {
int count = 0;
for (int i = 0; i < 100
This is not a bug. The semicolon becomes the only "statement" in the body of your for loop.
Write this another way to make it easier to see:
for (int i = 0; i < 100; i++)
;
{
count++;
}
The block with count++ becomes a bare block with a single statement, which isn't associated with the for loop at all, because of the semicolon. So this block, and the count++ within it, is only executed once.
This is syntactically valid java. for (int i = 0; i < 100; i++); is equivalent to:
for (int i = 0; i < 100; i++)
{ ; } // no statement in the body of the loop.
for loops of this form can be useful because of the side-effects within the loop increment statement or termination condition. For instance, if you wanted to write your own indexOfSpace to find the first index of a space character in a String:
int idx;
// for loop with no body, just incrementing idx:
for (idx = 0; string.charAt(idx) != ' '; idx++);
// now idx will point to the index of the ' '