Java Reference
In-Depth Information
if (inputMsgSize == 0) {
}
...
}
// The next statement refers to inputMsgSize outside the whole if statement
// and would be invalid as well.
if (inputMsgSize == 0) {
...
}
Note that local variables cannot be defined inside a code block and later evalu-
ated outside it. This sort of result state variable must be defined outside the code
block if it is to be used outside the code block.
If an inner code block were to attempt to define a new local variable with the
same name as an existing variable ( inputMsgSize , in the example), then the Java
compiler would detect that as a name collision and report an error. This is, by the
way, a departure from some C and C++ compilers, where local variables can be
named the same as existing variables—a source of more than a few bugs.
Finally, a local variable named inputMsgSize could be defined in some other
code block and used inside that code block. This often happens with temporary
variables and counters, such as the commonly used x. Java's tight scoping rules
should allow the compiler to catch most instances of inappropriate use (and reuse)
of local variables.
T HE WHILE S TATEMENT
Structure: while (condition) { block } ;
This basic loop control statement will evaluate condition and, if true, will per-
form the block of code. Let's hope that some statement in the block of code will
eventually cause condition to not be true, or else you would have an endless loop!
// Assume errorMsgs is an array of ErrorMsg objects that has previously
// been created
// ARRAY_SIZE is the maximum number of elements allowed in ErrorMsg.
// Examine each ErrorMsg object to find the first with a size equal to 0.
// Define x outside the while code block.
int x = 0;
while (x < ARRAY_SIZE) {
Search WWH ::




Custom Search