Computer Science
With reference to switch case, explain the following:
(a) Default case
(b) Fall through
Answer
(a) Default case
When none of the case values are equal to the expression of switch statement then default case is executed. In the example below, value of number is 4 so case 0, case 1 and case 2 are not equal to number. Hence SOPLN of default case will get executed printing "Value of number is greater than two" to the console.
int number = 4;
switch(number) {
case 0:
System.out.println("Value of number is zero");
break;
case 1:
System.out.println("Value of number is one");
break;
case 2:
System.out.println("Value of number is two");
break;
default:
System.out.println("Value of number is greater than two");
break;
}
(b) Fall through
break statement at the end of case is optional. Omitting break leads to program execution continuing into the next case and onwards till a break statement is encountered or end of switch is reached. This is termed as Fall Through in switch case statement.
int number = 1;
switch(number) {
case 1:
System.out.println("Value of number is one");
case 2:
System.out.println("Value of number is two");
break;
case 3:
System.out.println("Value of number is three");
case 4:
System.out.println("Value of number is four");
break;
default:
System.out.println("Value of number is greater than four");
break;
}
In the above example, as number is 1, case 1 matches and Value of number is one
gets printed. But as there is no break in case 1 so program control falls through to case 2 and Value of number is two
also gets printed. Case 2 has a break statement that transfers the program control to the end of switch-case statement. This continuation of program execution to case 2 is termed as Fall through.
Related Questions
What are the advantages of Scanner Class? Explain.
Distinguish between:
Finite loop and Infinite loop
What is a token? Explain these methods while reading token from Scanner object.
(a) nextlnt( ) (b) nextDouble( )
(c) next( ) (d) nextLine( )Distinguish between:
Exit controlled loop and Entry controlled loop