Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
public static void main(String args[]) {
int a, b;

for(a=1, b=4; a<b; a++,b--) {
System.out.println("a = " + a);
System.out.println("b = " + b);
}
}
}


In this example, the initialization portion sets the values of bothaandb. The two comma-
separated statements in the iteration portion are executed each time the loop repeats. The
program generates the following output:


a = 1
b = 4
a = 2
b = 3

NOTEOTE If you are familiar with C/C++, then you know that in those languages the comma is an
operator that can be used in any valid expression. However, this is not the case with Java. In
Java, the comma is a separator.


Some for Loop Variations
Theforloop supports a number of variations that increase its power and applicability. The
reason it is so flexible is that its three parts—the initialization, the conditional test, and the
iteration—do not need to be used for only those purposes. In fact, the three sections of the
forcan be used for any purpose you desire. Let’s look at some examples.
One of the most common variations involves the conditional expression. Specifically,
this expression does not need to test the loop control variable against some target value. In
fact, the condition controlling theforcan be any Boolean expression. For example, consider
the following fragment:


boolean done = false;


for(int i=1; !done; i++) {
// ...
if(interrupted()) done = true;
}


In this example, theforloop continues to run until thebooleanvariabledoneis set totrue.
It does not test the value ofi.
Here is another interestingforloop variation. Either the initialization or the iteration
expression or both may be absent, as in this next program:


// Parts of the for loop can be empty.
class ForVar {
public static void main(String args[]) {
int i;


Chapter 5: Control Statements 91

Free download pdf