Java Reference
In-Depth Information
The last rule is what makes a
switch
statement unique. The value being switched on is
compared for equality to each
case
statement in the order that they appear. Once a
case
statement is
true
, no subsequent
case
statements are tested. All statements following a true
case
execute, even if control “falls through” other
case
statements, until a
break
occurs.
Let's look at an example. The following code switches on an
int
. See if you can
determine the output:
6. int x = 0;
7. switch(x) {
8. case 0 :
9. case 1 :
10. System.out.println(“0 or 1”);
11. break;
12. case 2 :
13. System.out.println(“2”);
14. case 3 :
15. System.out.println(“2 or 3”);
16. break;
17. default :
18. System.out.println(“default”);
19.}
20.System.out.println(“After switch”);
Here is the fl ow of control that occurs when this code executes:
1.
The
int x
is declared and assigned the value
0
.
2.
The
case 0
is true on line 8, so no more cases are tested for equality.
3.
x
does not equal
1
on line 9, but
x
is not compared to
1
on line 9. Instead, control just
falls through to line 10.
4.
0 or 1
is printed on line 10.
5.
The
break
is hit on line 11, causing control to jump out of the
switch
statement down
to line 20 and
After switch
is printed.
Therefore, the output of this switch is
0 or 1
After switch
Using the same
switch
statement, the following output displays when
x
equals
2
:
2
2 or 3
After switch
Search WWH ::
Custom Search