I wrote the following class:
public class TestOne {
public static void main(String[] args) {
int count = 0;
for (int i = 0; i < 100; i++) {
count++;
}
System.out.println(count);
}
}
The output is 100.
Then I added a semicolon:
public class TestOne {
public static void main(String[] args) {
int count = 0;
for (int i = 0; i < 100; i++); { // <-- Added semicolon
count++;
}
System.out.println(count);
}
}
The output is 1.
The result is unbelievable. Why does this added semicolon change the meaning of my program so dramatically?
This is not a bug. The semicolon becomes the only “statement” in the body of your
forloop.Write this another way to make it easier to see:
The block with
count++becomes a bare block with a single statement, which isn’t associated with theforloop at all, because of the semicolon. So this block, and thecount++within it, is only executed once.This is syntactically valid java.
for (int i = 0; i < 100; i++);is equivalent to:forloops 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 ownindexOfSpaceto find the first index of a space character in aString: