Java Reference
In-Depth Information
This loop performs no iterations at all. It will not cause an execution error; it just
won't execute the body. It initializes the variable to 1 and tests to see if this is less than
or equal to 0 . It isn't, so rather than executing the statements in the body, it stops there.
When you construct a for loop, you can include more than one statement inside
the curly braces. Consider, for example, the following code:
for (int i = 1; i <= 20; i++) {
System.out.println("Hi!");
System.out.println("Ho!");
}
This will produce 20 pairs of lines, the first of which has the word “Hi!” on it and
the second of which has the word “Ho!”
When a for loop controls a single statement, you don't have to include the curly
braces. The curly braces are required only for situations like the previous one, where
you have more than one statement that you want the loop to control. However, the
Sun coding convention includes the curly braces even for a single statement, and we
follow this convention in this topic. There are two advantages to this convention:
Including the curly braces prevents future errors. Even if you need only one state-
ment in the body of your loop now, your code is likely to change over time.
Having the curly braces there ensures that, if you add an extra statement to the
body later, you won't accidentally forget to include them. In general, including
curly braces in advance is cheaper than locating obscure bugs later.
Always including the curly braces reduces the level of detail you have to consider
as you learn new control structures. It takes time to master the details of any new
control structure, and it will be easier to master those details if you don't have to
also be thinking about when to include and when not to include the braces.
Common Programming Error
Forgetting Curly Braces
You should use indentation to indicate the body of a for loop, but indentation alone
is not enough. Java ignores indentation when it is deciding how different statements
are grouped. Suppose, for example, that you were to write the following code:
for (int i = 1; i <= 20; i++)
System.out.println("Hi!");
System.out.println("Ho!");
The indentation indicates to the reader that both of the println statements
are in the body of the for loop, but there aren't any curly braces to indicate that
to Java. As a result, this code is interpreted as follows:
Continued on next page
 
Search WWH ::




Custom Search