Java Reference
In-Depth Information
Because the value of
i
is 50, which does not match any of the
case
labels, the execution starts at the first
statement after
default
label. The control falls through the subsequent label
case 20:
and executes the statement
following this case label, which prints
"Twenty"
. Generally, you want to print
"Ten"
if the value of
i
is 10 and
"Twenty"
if the value of
i
is
20
. If the value of
i
is not
10
and 20, you want to print
"No-match"
. This is possible using a
break
statement inside
switch
statement. When a
break
statement is executed inside a
switch
statement, the control is
transferred outside the
switch
statement. For example,
int i = 10;
switch (i) {
case 10:
System.out.println("Ten");
break; // Transfers control outside the switch statement
case 20:
System.out.println("Twenty");
break; // Transfers control outside the switch statement
default:
System.out.println("No-match");
break; // Transfers control outside the switch statement. It is not necessary.
}
Ten
Note the use of the
break
statement in the above snippet of code. In fact, the execution of a
break
statement
inside a
switch
statement stops the execution of the switch statement and transfers control to the first statement, if
any, following the switch statement. In the above snippet of code, the use of a
break
statement inside the
default
label is not necessary because the
default
label is the last label in the
switch
statement and the execution of the
switch
statement will stop after that anyway. However, it is recommended to use a
break
statement even inside the
last label to avoid errors if additional labels are added later.
The value of the constant expressions used as the
case
labels must be in the range of the data type of
switch-expression
. Keeping in mind that the range of the
byte
data type in Java is -128 to 127, the following code
would not compile because the second
case
label is
150
, which is outside the range of the
byte
data type:
byte b = 10;
switch (b) {
case 5:
b++;
case 150: // A compile-time error. 150 is greater than 127
b--;
default:
b = 0;
}