A switch statement allows a variable to be tested for equality against multiple values. It provides the case for the different blocks of code to be executed.
Switch expression and case value must be of the same type. There must be at least one case or multiple cases with unique case values. In the end, it can have a default case which is optional that is executed if no cases are matched.
It can also have an optional break that is useful to exit the switch otherwise it continues to the next case.
Flowchart for switch statement in java:
Syntax of switch statements:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | { case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional . . . . case valueN: //code to be executed; break; //optional default: code to be executed if all cases are not matched; } |
Example of a switch-case statement in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | public class SwitchTest { public static void main(String[] args) { int num = 5; //Switch expression switch(num) { //Case statements case 3: System.out.println("Number 3"); break; case 5: System.out.println("Number 5"); break; case 8: System.out.println("Number 8"); break; //Default case default: System.out.println("Not matched"); } } } |
Output switch-case statement:
1 | Number 5 |
For practice you can look at this article: Currency Conversion Program in Java