Java Reference
In-Depth Information
How It Works
Now take a look at how it works.
1.
The application begins by executing the
main
method, which in this case is the only method.
2.
The first statement begins with a
for
loop.
3.
The iterator, named
i
, begins at value
1
and checks the termination condition. 1 is less than or
equal to 10, so you enter the loop.
4.
In the first statement inside the loop, a second
int
, named
doubled
, is assigned the value of
i
*2. In
this first iteration,
i
= 1, so
doubled
=
2
.
5.
In the next statement of the loop, there is a
println
command. A line is output to the console that
reads:
1 times two equals 2
. Because the command is
println
instead of
print
, you can imag-
ine pressing Enter or Return at the end of the string to create a new line.
6.
The program reaches the end of the loop, and because the iteration of the loop is
i
++
, 1 is added to
the value of
i
. The iterator
i
is reassigned the value of 1+1 or 2.
7.
The termination condition is evaluated again. Because 2 is still less than or equal to 10, you will go
through the loop again.
8.
The variable
doubled
is 2*2 or 4 this time.
9.
Another line will be output to the console, this time reading:
2 times two equals 4
.
10.
This will continue until
i
++ = 11
, when the termination condition will evaluate to
false
and the
loop will not be entered anymore. At that time, the loop will be skipped over and the program will
proceed with the final statement. One final line will be output to the console, indicating the end of
the program.
What Is an enhanced for Loop?
There is an alternate form, called an enhanced
for
loop, that was introduced specifically for arrays
and other iterable objects. Instead of the index initialized as part of the standard
for
loop, enhanced
for
loops use an iterator. Unlike the index of a standard
for
loop, the iterator does not require ini-
tialization, termination, or increment, as it will automatically iterate through all elements in the array.
Note that rather than an integer index, the iterator is the same type as the elements in the array or
other Iterable object. From the previous example, this second form would be coded as follows:
for (int i: sales2014){
salesPerStaff[i] = sales2014[i]/staff2014[i];
totalSales2014 = totalSales2014 + sales2014[i];
}
This can be read in English as, “For each
int
in the
sales2014
array, do the following. . .” The
array can contain other data types or objects.
Search WWH ::
Custom Search