Java Reference
In-Depth Information
This flow control statement is commonly used to perform various functions
based on the value in a variable. It is similar to COBOL's EVALUATE verb.
expression
is evaluated and then compared for equality to each of the
case
state-
ments. If
expression
is equal to the
case
statement, the code block for that state-
ment is performed.
int inputMsgSize = 0;
int x = 0;
for (x = 0; x < ARRAY_SIZE ; x++) {
switch ( errorMsgs[x].msgSize)
{
case 0:
errorMsgs[x].setErrorMsg("Default Text");
break;
case 1:
case 2:
case 3:
errorMsgs[x].setErrorMsg("Text < 4 chars");
break;
default:
}
}
This statement does have a number of limitations. You can evaluate only cer-
tain primitive types (
char
,
byte
,
short
,
int
) and enumerated types. You cannot use
ranges of values, as is possible with Level 88s in COBOL. And there are a few sur-
prising little side effects, depending on whether the
break
statement is performed.
Normally, each code block is coded with a
break
in order to exit the
switch
loop. If a break is not defined, then upon completion of the case code block, the
evaluation continues with the next case condition. This may or may not be what
you intended, so you should always place breaks in
case
statements; and if you want
evaluation to continue, make sure that you document it.
T
HE BREAK
,
CONTINUE
S
TATEMENTS
I've introduced the statements
break
and
continue
by example rather than with a
formal definition, so let's address these statements. These are statements that man-
age flow control in all the loop structures (
while
,
for
,
switch
, and so forth). The