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 declaration statement, as described on
page 170. For example, if i and j are 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 expression 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());
}
This will not compile: In a variable declaration the comma separates the different variables being declared,
and Cell is a type, not a variable. Declarations of different types of variables are distinct statements
terminated by semicolons. If you change the comma to a semicolon, however, you get a for loop with four
sections, not threestill an error. If you need to initialize two different types of variables then neither of them
can be declared within the for loop:
int i;
Cell node;
for (i = 0, node = head;
i < MAX && node != null;
i++, node = node.next)
{
System.out.println(node.getElement());
}
Typically, the for loop is used to iterate a variable over a range of values until some logical end to that range
is reached. You can define what an iteration range is. A for loop is often used, for example, to iterate
through the elements of a linked list or to follow a mathematical sequence of values. This capability makes the
for construct more powerful than equivalent constructs in many other languages that restrict for-style
constructs to incrementing a variable over a range of values.
Here is an example of such a loop, designed to calculate the smallest value of exp such that 10exp is greater
than or equal to a value: