GuidePedia

0



Switch statement in Java|| The switch statement is another conditional structure. it is good of alternate of nested if-else .it can be used easily when there are many choices available and only one should be executed. Nested if it becomes very difficult in such a situation. If the statement makes a selection based on a single true or false condition. there are four cases of computing taxes which depends on the value of status .to full account for all cases nested if statement were used. Overuse of nested if statement makes a program difficult to read java provide the switch statement for handle the multiple conditions efficiently.

STRUCTURE OF SWITCH STATEMENT.











EXAMPLE.






FLOWCHART.











Working of a switch statement.
The switch statement compares the result of a single expression with multiple choice. The expression can be any valid expression that results in integer or character value.  the expression is evaluated at the top of the switch statement and its the result is compared with a different case. each represents one choice. if the result matches  with any case, the corresponding block of statement is executed .any no of cases can be used in one switch statement .the default the label appears  at the end of all  case blocks.it is executed only when the result of expression does not match with any case label .its used is optional .the positional of default label is not fixed.it may be placed before the first case a statement or after the last one. The break statement used in each case is used to exit from the switch body.it is used at the end of each case block. when the result of the expression matches with a case a block, the corresponding statement is executed. The break statement comes after these statements and control exit from the switch body .if breaks are not used all case blocks that come after the matching case will also be executed.

The switch statement observes the following rule.
  • ·         When the value in case in statement matches the value of switch expression the statement starting from this case is executed until either a break statement or the end of the switch statement is reached
  • ·         The keywords breaks are optional .the break statement immediately ends the switch statement.
  • ·         The default case which is optional can be used to perform an action when none of the Specified cases match the switch expression.


RELATED LECTURE.

Post a Comment

THANKS FOR COMMENT

 
Top