Page 105 - 2617_JSSPS_C-7
P. 105
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 with the Start
switch keyword to define a case.
The switch statement also uses the
break and default keywords. The
break keyword is used to stop the Conditional
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
Case-2 Statement-2 Break
[statements]
break;
Unmatched
case value2:
[statements] Matched
Case-n Statement-n Break
break;
.. .. ...
Unmatched
.. .. ...
case valueN:
Default Statement
[statements]
break;
default: Flowchart of the switch statement Stop
[statements]
}
Program 8: Write a program to check the day based on the number entered by the user.
1 public class SwitchStatement
2 {
3 public static void main(int dayNumber)
4 {
Java Programming 103

