Beruflich Dokumente
Kultur Dokumente
2
The Switch Statement
• Each case
contains a value switch ( expression ){
and a list of case value1 :
statements statement-list1
case value2 :
• The flow of control statement-list2
case value3 :
transfers to statement-list3
statement case ...
associated with
the first case value }
that matches
3
Switch - syntax
• The general syntax of a switch statement is:
switch
switch ( expression ){
and case value1 :
case
statement-list1
are case value2 :
reserved statement-list2
words case value3 :
statement-list3
case ...
If expression
} matches value3,
control jumps
to here
The Switch Statement
• The break statement can
switch ( expression ){
be used as the last
case value1 :
statement in each case's statement-list1
statement list break;
case value2 :
• A break statement statement-list2
causes control to transfer break;
to the end of the switch case value3 :
statement statement-list3
break;
• If a break statement is case ...
not used, the flow of
control will continue into }
the next case
Switch Example
• Examples of the switch statement:
switch (option){
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
}
Switch – no breaks!!!
• Another Example:
switch (option){
case 'A': switch (option){
aCount++; case 'A':
break; aCount++;
case 'B': case 'B':
bCount++; bCount++;
break; case 'C':
case 'C': cCount++;
cCount++; }
break;
}
Switch - default
• A switch statement can have an optional
default case
• The default case has no associated value and
simply uses the reserved word default
To switch or not to
switch, that’s the
question….
java/Switch/SwitchExample.java
SwitchNboolean.java
SwithcNothers.java