Switch Statements: Comparing Exact Values
Switch Statements: Comparing Exact Values
evaluates an expression,
then attempts to match the
result to one of several
possible cases
switch ( expression ){
case value1 :
statement-list1
case value2 :
statement-list2
case value3 :
statement-list3
case ...
}
contains a value
and a list of
statements
transfers to
statement
associated with
the first case value
that matches
switch ( expression ){
case value1 :
statement-list1
case value2 :
statement-list2
case value3 :
statement-list3
case ...
}
Switch - syntax
The general syntax of a switch statement is:
switch
and
case
are
reserved
words
switch ( expression ){
case value1 :
statement-list1
case value2 :
statement-list2
case value3 :
statement-list3
case ...
}
If expression
matches value3,
control jumps
to here
switch ( expression ){
case value1 :
statement-list1
break;
case value2 :
statement-list2
break;
case value3 :
statement-list3
break;
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':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
}
switch (option){
case 'A':
aCount++;
case 'B':
bCount++;
case 'C':
cCount++;
}
Switch - default
A switch statement can have an optional default
case
with
default
case:
switch (option){
case 'A':
aCount++;
break;
case 'B':
bCount++;
break;
case 'C':
cCount++;
break;
default:
otherCount++;
break;
}
Questions??
Toswitchornotto
switch,thatsthe
question.
java/Switch/SwitchExample.java
SwitchNboolean.java
SwithcNothers.java