Java Reference
In-Depth Information
In the preceding code the semicolons serve to delimit the initialization,
continuation, and update phases of the for loop. The initialization stage
( x =0, y = 5) sets the variables to their initial values. The continuation
stage (x< 5) tests the condition during which the loop continues. The up -
date stage ( x ++, y--) increments x and decrements y during each itera-
tion. The comma operator is used to separate the components in each
loop phase.
The middle phase in the for loop statement, called the test expression,
is evaluated during each loop iteration. If this statement is false, then the
loop terminates immediately. Otherwise, loop continues. For the loop to
execute the first time the test expression must initially evaluate to true.
Note that the test expression determines the condition under which the
loop executes, rather than its termination. For example
for(x = 0; x == 5; x++)
System.out.println(x);
The println() statement in the preceding loop does not execute be-
cause the test expression x == 5 is initially false. The following loop, on
the other hand, executes endlessly because the terminating condition is
assigned a new value during each iteration.
int x;
for(x=0;x=5;x++)
System.out.println(x);
Programmers note:
In the preceding loop the middle element should have been x= = 5.
Thestatement x =5assignsavalueto x andalwaysevaluatestrue.Itis
averycommonmistaketousetheassignmentoperator(=)inplaceof
the comparison operator (= =).
It is also possible for the test element of a for loop to contain a com-
plex logical expression. In this case, the entire expression is evaluated to
determine if the condition is met. For example:
int x, y;
for(x = 0,y=5;(x<3||y>1);x++, y--)
The test expression
(x<3||y>1)
evaluates to true if either xis less than 3 or if y is greater than 1. The values
that determine the end of the loop are reached when the variable x =4or
when the variable y =1.
Search WWH ::




Custom Search