Computer Applications
Is it necessary to include default case in a switch statement? Justify.
Answer
default case is optional in a switch statement. If no case is matched in the switch block for a given value of control variable, default case is executed implicitly.
Consider the below example:
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;
}
Here, value of number is 4 so case 0, case 1 and case 2 are not equal to number. Hence println() of default case will get executed printing "Value of number is greater than two" to the console. If we don't include default case in this example then also the program is syntactically correct but we will not get any output when value of number is anything other than 0, 1 or 2.