Page 78 - iPlus_Ver_2.0_class_8
P. 78
Run this program four times with the inputs 'W', 'R',
'S', and 'T', respectively. You will see the output as
“Enjoy Winter”, “Enjoy Rainy”, “Enjoy Summer” and
“Invalid Character” respectively. This is because each
time the condition is checked with the conditional
expression written after the if and else…if keywords, it
executes the statements written inside the block
where a perfect match is found.
The switch Statement
Using the long if…else ladder becomes tedious. It makes the code more complex. Java provides a
new statement called switch. The switch statement is used as the substitute for the if…else ladder.
It is a multi-way branch statement that allows a variable to be checked for equality with a list of
values. Each value in the list is called
a case. The case keyword is used Start
with the switch keyword to define a
case. The switch statement also uses
the break and default keywords. The
Conditional
break keyword is used to stop the
Expression
execution of the switch statement
when a matched case is found. On
the other hand, the default keyword
is used to specify some code to be
executed if there is no matched Case-1 Matched Statement-1 Break
case found. The syntax of the switch
statement is as follows:
Unmatched
switch (variable) {
case value1:
Matched
[statements] Case-2 Statement-2 Break
break;
case value2: Unmatched
[statements]
break; Matched
Case-n Statement-n Break
.. .. ...
.. .. ...
case valueN: Unmatched
[statements]
break; Default Statement
default:
[statements]
} Flowchart of the switch statement Stop
76
iPlus (Ver. 2.0)-VIII

