Page 82 - iPro_trackGPT_V5_Class8
P. 82
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 a long if...else ladder can be tiring and make your code more complicated. Java offers
a simpler option called the switch statement. This statement replaces the if…else ladder and allows
you to compare a variable to a list
of values. Each value in this list
Start
is referred to as a case. The case
keyword is used with the switch
keyword to define these cases.
The switch statement also uses Conditional
the break and default keywords. Expression
When a match is found, the
break keyword stops the switch
statement. The default keyword
is used to run some code if no Matched
Case-1 Statement-1 Break
cases match. The syntax of the
switch statement is as follows:
switch (variable) { Unmatched
case value1:
[statements] Matched
Case-2 Statement-2 Break
break;
case value2:
Unmatched
[statements]
break;
Matched Break
.. .. ... Case-n Statement-n
.. .. ...
case valueN: Unmatched
[statements]
break;
Default Statement
default:
[statements]
}
Stop
80 TrackGPT iPRO (V5.0)-VIII

