Java Reference
In-Depth Information
int inputMsgSize = myErrorMsg.msgSize;
...
}
else {
...
}
The variable
inputMsgSize
is valid only in the code block in which it has been
defined. In the example, that would be the first code block (that is, the statements
executed if
inputMsg
is equal to
“Any Text”
). Note that these statements are
bounded by the first pair of braces.
This variable is also valid in any
inner
code blocks. Therefore, a statement that
sets
inputMsgSize
to -1 in an inner code block is valid:
if (inputMsg.equals ("Any Text")) {
...
// The next statement defines a local variable inputMsgSize and sets it to
// msgSize.
int inputMsgSize = myErrorMsg.msgSize;
if (inputMsgSize == 0) {
// The next statement resets the local variable inputMsgSize.
inputMsgSize = -1;
...
}
...
}
else {
Outside the braces for the first code block (for example, in the
else
condition
code block), the variable
inputMsg
is not valid, and references to it would cause a
compile time error:
if (inputMsg.equals ("Any Text")) {
...
// The next statement defines a local variable inputMsgSize and sets it to
// msgSize.
int inputMsgSize = myErrorMsg.msgSize;
...
}
else {
// The next statement refers to inputMsgSize outside its code block
// and would cause a compile time error.