Switch
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression.
Syntax:
Rules:
The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression.
Each case value must be a unique literal (that is, it must be a constant, not a variable). Duplicate case values are not allowed.
Working:
The value of the expression is compared with each of the literal values in the case statements.
If a match is found, the code sequence following that case statement is executed.
If none of the constants matches the value of the expression, then the default statement is executed.
However, the default statement is optional. If no case matches and no default is present, then no further action is taken.
Note:
The break statement is used inside the switch to terminate a statement sequence.
When a break statement is encountered, execution branches to the first line of code that follows the entire switch statement. This has the effect of “jumping out” of the switch.Ex:
Example 1:
Compare if-else-if with switch:
If-else:
Same code with switch:
Note:
What will happen if break is removed ?
Examine and find the output of the below program:
Summary:
There are three important features of the switch statement to note:
The switch differs from the 'if', that switch can only test for equality, whereas if can evaluate any type of Boolean expression. That is, the switch looks only for a match between the value of the expression and one of its case constants.
No two case constants in the same switch can have identical values. Of course, a switch statement and an enclosing outer switch can have case constants in common.
A switch statement is usually more efficient than a set of nested ifs.
You can use a switch statement to compare the value of a variable with multiple values.For each of these values, you can define a set of statements to execute.
Last updated