Java Reference
In-Depth Information
with
salutation.length
, the number of elements in the
salutation
array. When the
index is equal to or greater than
salutation.length
, the loop is exited.
The final element of the
for
statement is
i++
. This causes the loop index to increment by
1 each time the loop is executed. Without this statement, the loop would never stop.
The statement inside the loop sets an element of the
salutation
array equal to
“Mr.”
.
The loop index is used to determine which element is modified.
Any part of the
for
loop can be an empty statement; in other words, you can include a
semicolon with no expression or statement, and that part of the
for
loop is ignored. Note
that if you do use an empty statement in your
for
loop, you might have to initialize or
increment any loop variables or loop indexes yourself elsewhere in the program.
You also can have an empty statement as the body of your
for
loop if everything you
want to do is in the first line of that loop. For example, the following
for
loop finds the
first prime number higher than
4,000
. (It employs a method called
notPrime()
, which
returns a Boolean value, presumably to indicate when
i
is not prime.)
for (i = 4001; notPrime(i); i += 2)
;
A common mistake in
for
loops is to accidentally put a semicolon at the end of the line
that includes the
for
statement:
4
for (i = 0; i < 10; i++);
x = x * i; // this line is not inside the loop!
In this example, the first semicolon ends the loop without executing
x = x * i
as part
of the loop. The
x = x * i
line is executed only once because it is outside the
for
loop
entirely. Be careful not to make this mistake in your Java programs.
The next project you undertake is a rewrite of the
HalfDollar
application that uses
for
loops to remove redundant code.
The original application works only with an array that is three elements long. The
new version, shown in Listing 4.3, is shorter and more flexible (but it returns the same
output).
LISTING 4.3
The Full Text of
HalfLooper.java
1: class HalfLooper {
2: public static void main(String[] arguments) {
3: int[] denver = { 2500000, 2900000, 3500000 };
4: int[] philadelphia = { 2500000, 2900000, 3800000 };
5: int[] total = new int[denver.length];
6: int sum = 0;