Java Reference
In-Depth Information
However, this situation does not diminish the usefulness of enhanced
for
statements. In
many programming situations, you iterate over a collection of data and do not need to
modify or delete elements in the collection, making an enhanced
for
loop the preferred
solution. They can also make your code more readable when iterating over nested
collections, as shown in the next section. The general rule of thumb is to use enhanced
for
loops whenever you can!
Nested Enhanced
for
Loops
You really start to see the benefi t of the enhanced
for
syntax when iterating over tabular
data (with rows and columns) using nested loops. The following example uses nested
enhanced
for
loops to display a multiplication table of the numbers
1
to
9
. Examine the
code and see if you can determine its output:
3. int [] digits = {1,2,3,4,5,6,7,8,9};
4. for(int x : digits) {
5. for(int y : digits) {
6. System.out.print(x * y + â\tâ);
7. }
8. System.out.println();
9. }
The
digits
array has nine elements, so the outer loop on line 4 iterates nine times and
so does the inner loop on line 5. Therefore, line 6 executes
9 * 9 = 81
times. The fi rst time
through the outer loop,
x
is
1
and
y
goes from
1
to
9
, printing
1*1
,
1*2
,
1*3
, and so on up
to
1*9
. This process repeats for
x
equal to
2
, printing
2*1
,
2*2
,
2*3
, and so on up to
2*9
.
The process keeps repeating until the following multiplication table displays:
1 2 3 4 5 6 7 8 9
2 4 6 8 10 12 14 16 18
3 6 9 12 15 18 21 24 27
4 8 12 16 20 24 28 32 36
5 10 15 20 25 30 35 40 45
6 12 18 24 30 36 42 48 54
7 14 21 28 35 42 49 56 63
8 16 24 32 40 48 56 64 72
9 18 27 36 45 54 63 72 81
I could have just as easily written this example using basic
for
loops, and before Java 5.0
it would have been the only option! But I like the enhanced
for
loop for its simplicity and
readability. Make sure you understand the details of the enhanced
for
statement. As I have
mentioned before, the newer Java topics tend to be emphasized on the SCJP exam.
Next we discuss another popular looping control structure: the
while
statement.
Search WWH ::
Custom Search