Java Reference
In-Depth Information
If the integer expression in the switch parameter returns the value 1, then the
processing jumps to statement1 ,which has the label case 1 .Ifitreturns 2,
then processing starts with statement2 .Ifthe value does not match any label
value, then the processing goes to statement3 with the default label.
Note that processing continues on to statements that follow it in subsequent
case labeled sections unless a break statement causes the process to jump out
of the switch area. In this example,
switch (i) {
case 1: m = 5;
case 2: j = 5;
break;
default: j = 2;
}
If i equals 1 the m = 5 statement is evaluated and then the j = 5 statement
is evaluated as well. The break sends the processing out of the switch section.
Most of the time, there are break statements at the end of each case label. Also,
most case sections consist of multiple lines of code. It is not necessary to enclose
those lines in braces. For example, the following is perfectly legal and works as
expected:
switch (i) {
case 1:
m = 5;
q = 6;
break;
case 2:
j = 5;
k = 6;
break;
}
Note that the default label is not required, though it is good practice to use one
in every switch statement.
The type of the variable i in the switch statement must be byte , short ,
int ,or char type. The long type, boolean ,any floating-point type, and object
references are not permitted (but see the autoboxing discussion in Chapter 3 for
J2SE 5.0).
2.10 Casts and mixing
Now that we have presented an overview of the basic elements and structures of
the language we can look a bit more closely at how the data types work. Here we
Search WWH ::




Custom Search