demonstrate an example of break and default statement in fall through switch casedemonstrate an example of break and default statement in fall through switch case
pls answer quick
Answers
Answer:
Following rules govern the fall through the behavior of switch statement.
When the variable being switched on is equal to a case, the statements following that case will execute until a break statement is reached.
When a break statement is reached, the switch terminates, and the flow of control jumps to the next line following the switch statement.
Not every case needs to contain a break. If no break appears, the flow of control will fall through to subsequent cases until a break is reached.
Answer:
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:
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.
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.
switch case flow diagram
Break statement in Switch Case
Break statement is optional in switch case but you would use it almost every time you deal with switch case. Before we discuss about break statement, Let’s have a look at the example below where I am not using the break statement:
public class SwitchCaseExample2 {
public static void main(String args[]){
int i=2;
switch(i)
{
case 1:
System.out.println("Case1 ");
case 2:
System.out.println("Case2 ");
case 3:
System.out.println("Case3 ");
case 4:
System.out.println("Case4 ");
default:
System.out.println("Default ");
}
}
}
Output:
I hope it's helpful for you