Java Reference
In-Depth Information
In the program, pay special attention to this line:
Notice how
x
is declared. It is a reference to a one-dimensional array of integers. This is
necessary because each iteration of the
for
obtains the next
array
in
nums
, beginning with
the array specified by
nums[0]
. The inner
for
loop then cycles through each of these ar-
rays, displaying the values of each element.
Applying the Enhanced for
Since the for-each style
for
can only cycle through an array sequentially, from start to fin-
ish, you might think that its use is limited. However, this is not true. A large number of
algorithms require exactly this mechanism. One of the most common is searching. For ex-
ample, the following program uses a
for
loop to search an unsorted array for a value. It
stops if the value is found.