Java Reference
In-Depth Information
}
else {
x++;
}
}
while (x < ARRAY_SIZE);
In this example,
inputMsgSize
will be set at least once. Since it has been defined
outside the
do...while
loop, it will be valid outside the loop and will always contain
some value as set in the loop.
T
HE FOR
S
TATEMENT
Structure: for (expression1; (condition); expression2) { block }
This loop control statement is commonly used to support iteration. The first ex-
pression is the counter initialization and is performed only at the start of the loop.
The condition is tested to determine if the loop should continue, and if true, the
code block is performed. The second expression is the expression that changes the
counter. It is performed after the code block is completed, but before the next iter-
ation of the loop. The code block will be performed iteratively as long as
condition
is true. After every iteration of the code block, and if
condition
is true, the counter
increment expression (
expression2
) will be performed.
for (int x = 0; x < ARRAY_SIZE ; x++) {
int inputMsgSize = errorMsgs[x].msgSize;
if (inputMsgSize == 0) {
// Exit the loop immediately. x will point to this element.
break;
}
}
Note that the sample is not of much use, since both
x
and
inputMsgSize
have been
defined inside the loop and are, therefore, not available outside it (
x
was actually
implicitly defined in the
for
statement). If you tried to use either
x
or
inputMsgSize
outside the loop, you would create a compiler error.
It would be necessary to define these variables before the loop if you want to use
them after it is complete.