Switch case statement is used when we have number of options (or choices) and we may need to perform a different task for each choice.
The syntax of Switch case statement looks like this –
switch (variable or an integer expression)
{
case constant:
//Java code
;
case constant:
//Java code
;
default:
//Java code
;
}
Switch Case statement is mostly used with break statement even though it is optional. We will first see an example without break statement and then we will discuss switch case with break
A Simple Switch Case Example
public class SwitchCaseExample1 {
public static void main(String args[]){
int num=2;
switch(num+2)
{
case 1:
System.out.println("Case1: Value is: "+num);
case 2:
System.out.println("Case2: Value is: "+num);
case 3:
System.out.println("Case3: Value is: "+num);
default:
System.out.println("Default: Value is: "+num);
}
}
}
Output:
Default: Value is: 2
Explanation: In switch I gave an expression, you can give variable also. I gave num+2, where num value is 2 and after addition the expression resulted 4. Since there is no case defined with value 4 the default case got executed. This is why we should use default in switch case, so that if there is no catch that matches the condition, the default block gets executed.
Switch Case Flow Diagram
First the variable, value or expression which is provided in the switch parenthesis is evaluated and then based on the result, the corresponding case block is executed that matches the result.