Java The Complete Reference, Seventh Edition

(Greg DeLong) #1
The output from the program is shown here.

Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55

As this output shows, the for-each styleforautomatically cycles through an array in sequence
from the lowest index to the highest.
Although the for-eachforloop iterates until all elements in an array have been examined,
it is possible to terminate the loop early by using abreakstatement. For example, this program
sums only the first five elements ofnums:

// Use break with a for-each style for.
class ForEach2 {
public static void main(String args[]) {
int sum = 0;
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

// use for to display and sum the values
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
if(x == 5) break; // stop the loop when 5 is obtained
}
System.out.println("Summation of first 5 elements: " + sum);
}
}

This is the output produced:

Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Summation of first 5 elements: 15

As is evident, theforloop stops after the fifth element has been obtained. Thebreakstatement
can also be used with Java’s other loops, and it is discussed in detail later in this chapter.
There is one important point to understand about the for-each style loop. Its iteration
variable is “read-only” as it relates to the underlying array. An assignment to the
iteration variable has no effect on the underlying array. In other words, you can’t change

94 Part I: The Java Language

Free download pdf