Java Reference
In-Depth Information
D.3.3 for
The
for loop
has two different forms. The first form is also known as a
for-each loop
and is used
exclusively to iterate over elements of a collection. The loop variable is assigned the value of
successive elements of the collection on each iteration of the loop.
for
(
variable-declaration
:
collection
) {
statements
}
Example:
for
(String note : list) {
System.out.println(note);
}
No associated index value is made available for the elements of the collection. A for-each loop
cannot be used if the collection is to be modified while it is being iterated over.
The second form of for loop executes as long as a
condition
evaluates to
true
. Before the loop
starts, an
initialization statement
is executed exactly once. The
condition
is evaluated before
every execution of the loop body (so the statements in the loop's body may execute zero times).
An
increment statement
is executed after each execution of the loop body.
for
(
initialization
;
condition
;
increment
) {
statements
}
Example:
for
(
int
i = 0; i < text.size(); i++) {
System.out.println(text.get(i));
}
Both types of for loop are commonly used to execute the body of the loop a definite number
of times—for instance, once for each element in a collection—although a for loop is actually
closer in effect to a while loop than to a for-each loop.
D.4 Exceptions
Throwing and catching exceptions provides another pair of constructs to alter control flow.
However, exceptions are primarily used to anticipate and handle error situations rather than the
normal flow of control.
try
{
statements
}
catch
(
exception-type name
) {
statements
}
Search WWH ::
Custom Search