Page 80 - Trackpad_ipro 4.1_Class8
P. 80
System.out.println("Enjoy Rainy");
}
else if (C == 'S')
{
System.out.println("Enjoy Summer");
}
else
{
System.out.println("Invalid Character");
}
}
}
Run this program four times with the inputs 'W',
'R', 'S', and 'T'. 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 against the conditional
expressions 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...if' ladder becomes tedious and makes the code more complex. The switch
statement is used as substitute for the 'if...else...if' 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 with the 'switch' keyword to define a case. The switch statement also
uses 'break' and 'default' keywords. The 'break' keyword is used to stop the execution of 'switch'
statement when a matched case is found. On the other hand, 'default' keyword is used to specify
some code to be executed if there is no matched case found.
The syntax of the switch statement is as follows:
switch (variable) {
case value1:
[statements]
break;
case value2:
[statements]
break;
.. .. ...
.. .. ...
case valueN:
78 iPro (Ver. 4.1)-VIII

