for (i =1; i <= 10; i++);
System.out.println("i is: + i);
This code will execute the for loop and do nothing each time through. This is because the extra semicolon at the end is an empty statement, which does nothing. Then after loop is finished, the code will print
i is 11
The correct way to indent the code so it accuratly shows the execution would be:
for (i =1; i <= 10; i++)
; // this is the empty statement
System.out.println("i is: + i);
An Example Infinite Loop
for (i = 1; i != 30; i = i + 5)
System.out.println("i is: + i);
Draw it and you will see. A much safer way to write the loop would be to use
<=, as shown in Figure 7-7.
Not an Infinite Loop
for (i = 1; i <= 30; i = i + 5)
System.out.println("i is: + i);
Although it is still probably wrong (it prints 1, then 6,
then 11, ...) it is not infinite, like the previous example.
for (i = 1; i <= numTimes; i++)
System.out.println("i is: + i);
Since the logical expression i <= numTimes ends up being
1 <= 0, and that evaluates false, the code inside the loop is
never executed.
There are other types of for loops that we will learn later, but remember that the classic for loop is used for counting. Sometimes, however you will want to execute code over again, but not execute it a certain number of times. This means that you will not use a counting loop. A while loop is used for this type of execution.