Java Reference
In-Depth Information
Some for Statement Notes
All of the three sections of a for statement are optional. If you don't need to initialize
a variable or update anything, you can leave those sections blank. For example, the
following for loop does not contain an update statement:
for(int i = 1; i <= 10; ) {
System.out.print(i++ + “,”);
}
The output of this loop is
1,2,3,4,5,6,7,8,9,10,
Updating the loop control variable within the loop defeats the purpose of the update
statement and makes your code more diffi cult to read, so this example is not something I
recommend using in the real world.
Also, the boolean expression of a for statement defaults to true if it is left blank. For
example, the following for statement is an infi nite loop:
for( ; ; ) {
System.out.print(“Hi”);
}
This particular loop will run until the JVM is terminated.
The Enhanced for Statement
Java 5.0 introduced a new looping control structure called the enhanced for statement , also
referred to as a for-each loop . An enhanced for statement is designed for iterating through
arrays and collections. The syntax is simpler than a basic for loop and makes your code
more readable. Figure 3.4 shows the syntax of an enhanced for statement.
FIGURE 3.4
The syntax of an enhanced for statement
The for keyword
Parentheses (required)
for( datatype iterator : collection ) {
//body of the loop
}
The iterator
automatically
initializes to the
next item in the
collection for each
iteration.
The array or iterable
collection being iterated
over
The data type
of the iterator
Search WWH ::




Custom Search