Java Reference
In-Depth Information
For example,
int i = 10;
switch (i) {
case 10: // Found the match
System.out.println("Ten"); // Execution starts here
case 20:
System.out.println("Twenty");
default:
System.out.println ("No-match");
}
Ten
Twenty
No-match
The value of
i
is 10. The execution starts at the first statement following
case 10:
and falls through
case 20:
and
default
labels executing the statements under these labels. If you change the value of
i
to 50, there would not be any
match in
case
labels and the execution would start at the first statement after the
default
label, which will print
"No-match"
. The following example illustrates this logic:
int i = 50;
switch (i) {
case 10:
System.out.println("Ten");
case 20:
System.out.println("Twenty");
default:
System.out.println("No-match"); /* Execution starts here */
}
No-match
The
default
label may not be the last label to appear in a
switch
statement and is optional. For example,
int i = 50;
switch (i) {
case 10:
System.out.println("Ten");
default:
System.out.println("No-match"); // Execution starts here
case 20:
System.out.println("Twenty");
}
No-match
Twenty