Computer Science
What is the purpose of default in a switch statement? Explain with the help of an example.
Answer
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 println statement 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;
}