What will happen if we do not use the break statement at the end of each case block of a switch case construct? Explain.
Answers
Switch case statements are used to execute only specific case statements based on the switch expression.
If we do not use break statement at the end of each case, program will execute all consecutive case statements until it finds next break statement or till the end of switch case block.
Explanation:
if you don't use the break statement after each case of a switch case construct,then a condition called fall through occurs.
for example:-
switch (v):
{
case 1:System.out.println("a");
case 2:System.out.println("b");
break;
}
when v=1,then
output: a
b
when v=2,then
output:b
so ,this condition in the absence of break word leads to the entry of flow of control inside the rest cases which is called fall through....
Note: fall through is not always disadvantageous!!!!!
for example:
if you desire to write a single statement for all cases,then
switch(c):
{
case 'a':
case 'e':
case 'i':
case 'o'
case 'u':System.out.println("vowels");
break;
}
THE ABOVE EXAMPLE IS AN EPITOME WHERE THERE IS ADVANTAGEOUS USE OF FALL THROUGH...
[in order to avoid writing,the statements in all cases,we have mentioned only in last case]