Java Reference
In-Depth Information
except that in a
for
statement the
update-expression
is always executed
The initialization and update parts of a
for
loop can be comma-separated
lists of expressions. The expressions separated by the commas are, like
most operator operands, evaluated from left-to-right. For example, to
march two indexes through an array in opposite directions, the following
code would be appropriate:
for (i = 0, j = arr.length - 1; j >= 0; i++, j--) {
// ...
}
The initialization section of a
for
loop can also be a local variable declar-
not used outside the
for
loop, you could rewrite the previous example
as:
for (int i = 0, j = arr.length - 1; j >= 0; i++, j--) {
// ...
}
If you have a local variable declaration, however, each part of the ex-
pression after a comma is expected to be a part of that local variable
declaration. For example, if you want to print the first
MAX
members of a
linked list you need to both maintain a count and iterate through the list
members. You might be tempted to try the following:
for (int i = 0, Cell node = head; // INVALID
i < MAX && node != null;
i++, node = node.next)
{
System.out.println(node.getElement());
}