Page 81 - TP_iPlus_V2.1_Class8
P. 81
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
Start
list is called a case. The case keyword
is used with the switch keyword to
define a case. The switch statement
also uses the break and default Conditional
keywords. The break keyword is used Expression
to stop the execution of the switch
statement when a matched case is
found. On the other hand, the default
keyword is used to specify some code Matched
to be executed if there is no matched Case-1 Statement-1 Break
case found. The syntax of the switch
statement is as follows:
Unmatched
switch (variable) {
case value1: Matched
Case-2 Statement-2 Break
[statements]
break;
Unmatched
case value2:
[statements]
break; Case-n Matched Statement-n Break
.. .. ...
.. .. ...
Unmatched
case valueN:
[statements]
Default Statement
break;
default:
[statements]
Flowchart of the switch statement Stop
}
79
Conditional, Looping and Jump Statements in Java

