THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

public static int tenPower(int value) {
int exp, v;
for (exp = 0, v = value - 1; v > 0; exp++, v /= 10)
continue;
return exp;
}


In this case, two variables step through different ranges. As long as the loop variable v is greater than zero,
the exponent value is incremented and v is divided by ten. When the loop completes, the value 10exp is the
smallest power of ten that is greater than or equal to value. Both the test value and the exponent are updated
on each loop iteration. In such cases, a comma-separated list of expressions is a good technique to ensure that
the two values are always in lockstep.


The body of this loop is simply a continue statement, which starts the next iteration of the loop. The body
of the loop has nothing to doall the work of the loop is in the test and iteration clauses of the for statement
itself. The continue style shown here is one way to show an empty loop body; another way is to put a
simple semicolon on a line by itself or to use an empty block with braces. Simply putting a semicolon at the
end of the for line is dangerousif the semicolon is accidentally deleted or forgotten, the statement that
follows the for can silently become the body of the for.


All the expressions in the for construct are optional. If initialization-expression or
update-expression is left out, its part in the loop is simply omitted. If loop-expression is left out,
it is assumed to be TRue. Thus, one idiomatic way to write an infinite loop is as a "for ever" loop:


for (;;)
statement


Presumably, the loop is terminated by some other means, such as a break statement (described later) or by
throwing an exception.


Conventionally, the for loop is used only when looping through a range of related values. It is bad style to
violate this convention by using initialization or increment expressions that are unrelated to the boolean loop
test.


Exercise 10.5: Write a method that takes two char parameters and prints the characters between those two
values, including the endpoints.


10.5.2. Enhanced for Statement


The enhanced for statement, often referred to as the for-each loop, provides an alternative, more compact
form for iterating through a set of values. It looks like this:


for (Type loop-variable : set-expression)
statement


The set-expression must evaluate to an object that defines the set of values that you want to iterate
through, and the loop-variable is a local variable of a suitable type for the set's contents. Each time
through the loop, loop-variable takes on the next value from the set, and statement is executed
(presumably using the loop-variable for something). This continues until no more values remain in the

Free download pdf