switch statement is a branch statement where there are multiple conditions in the form of cases. We can say that instead of using multiple if else if checks we can go with Switch statements.
switch statement can works with various datatypes like byte, short, int, long, String etc.
Syntax of switch statement
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
//if all cases failed this code will execute
}
break Keyword
break
keyword is used to breaks out of the switch block. This will stop the execution and checking for the next case in switch statement.
This is something like if condition matched then executed the code and break it because our job is done now.
Java Program to demonstrate switch statement
public class Main {
public static void main(String[] args) {
int number = 30;
switch (number) {
case 10:
System.out.println("Matched condition is 10");
break;
case 20:
System.out.println("Matched condition is 20");
break;
case 30:
System.out.println("Matched condition is 30");
break;
default:
System.out.println("No condition matched");
}
}
}
Output
Matched condition is 30
Some Switch Statement Rules
- Duplicate case/s values are not allowed in switch statement.
- Datatype of case and variable in the switch should be same.
- To terminate the statement break keyword should use otherwise other case will be checked and execute.
- default label is optional in switch statement.