Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
to use the loop control variable elsewhere in your program, you will not be able to declare
it inside theforloop.
When the loop control variable will not be needed elsewhere, most Java programmers
declare it inside thefor. For example, here is a simple program that tests for prime numbers.
Notice that the loop control variable,i, is declared inside theforsince it is not needed elsewhere.

// Test for primes.
class FindPrime {
public static void main(String args[]) {
int num;
boolean isPrime = true;

num = 14;
for(int i=2; i <= num/i; i++) {
if((num % i) == 0) {
isPrime = false;
break;
}
}
if(isPrime) System.out.println("Prime");
else System.out.println("Not Prime");
}
}

Using the Comma
There will be times when you will want to include more than one statement in the initialization
and iteration portions of theforloop. For example, consider the loop in the following program:

class Sample {
public static void main(String args[]) {
int a, b;

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

As you can see, the loop is controlled by the interaction of two variables. Since the loop is
governed by two variables, it would be useful if both could be included in theforstatement,
itself, instead ofbbeing handled manually. Fortunately, Java provides a way to accomplish
this. To allow two or more variables to control aforloop, Java permits you to include multiple
statements in both the initialization and iteration portions of thefor. Each statement is separated
from the next by a comma.
Using the comma, the precedingforloop can be more efficiently coded as shown here:

// Using the comma.
class Comma {

90 Part I: The Java Language

Free download pdf