Computer Science

With reference to switch case, explain the following:

(a) Default case

(b) Fall through

Java Conditional Stmts

3 Likes

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.

Answered By

3 Likes


Related Questions