The switch statement selects one of many code blocks to be executed. The switch statement contains multiple blocks of code called cases and a single case is executed based on the variable which is being switched.
Syntax :
switch(expression) {
case value1 :
// code blocks to be executed.
break; // optional
case value2 :
// code blocks to be executed.
break; // optional
// You can have any number of case statements.
default : // Optional
// code blocks to be executed.
}
The switch statement will be worded as below.
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the block of code inside case is executed.
- The break and default keywords are optional. Break statement terminates the switch block when the condition is satisfied.
It is optional. if not used, then next case is executed.
Comments