Page 195 - ComputerScience_Class_11
P. 195
{
case "ADD" : System.out.println(" Sum : "+(a+b));
break;
case "SUB" : System.out.println(" Difference : "+(a-b));
break;
case "MUL" : System.out.println(" Product : "+(a*b));
break;
case "DIV" : System.out.println(" Quotient : "+(a/b));
break;
default: System.out.println("You have entered wrong choice");
}
}
}
Depending on the operator, the respective case is called. If “ch” does not match any case, default is executed and
the message “You have entered wrong choice” will be printed.
Note: The data type of the expression or the variable provided in a switch statement can be int, char or
string. We cannot use real and boolean data types.
Fall Through
The break statement in a switch case construct represents the exit from the selected case. If we do not provide a break
statement after a case, it will not exit from the case and executes the rest of the cases. This situation of moving of
control from one case to another case in the absence of a “break” statement is known as Fall Through.
For example,
switch(ch)
{
case 1: System.out.println(5+6);
case 2: System.out.println(5-4);
break;
case 3: System.out.println(5*4);
default: System.out.println(5.0/6.0);
}
Here, if case 1 is selected, then both case 1 and case 2 will be executed. Hence, the result will be:
11
1
And the control will exit from the switch statement as the break is encountered.
Similarly, if case 3 is selected, then after the execution of case 3, the default case will also be executed.
Need of Fall Through Situation
Sometimes, we may need to execute two or more sequential cases together. Under such situations, if we exit from the
switch after executing one case, then the program snippet will not provide the desired result.
Statements and Scope 193

