Computer Applications

When does Fall through occur in a switch statement? Explain.

Java Conditional Stmts

15 Likes

Answer

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.

Consider the below example:

int day = 4;
    
switch(number) {

    case 1:
        System.out.println("Monday");
        
    case 2:
        System.out.println("Tuesday");

    case 3:
        System.out.println("Wednesday");
        
    case 4:
        System.out.println("Thursday");
      
    case 5:
        System.out.println("Friday");
        
    case 6:
        System.out.println("Saturday");
    
    case 7:
        System.out.println("Sunday");

    default:
        System.out.println("Invalid choice");
}

Output:

Thursday
Friday
Saturday
Sunday
Invalid choice

Explanation

Here, we have omitted break statement in all the cases. When the program executes with the control variable 4, the program prints 'Thursday' and falls through case 5, 6, 7 and default. Thus, 'Friday', 'Saturday', 'Sunday' and 'Invalid choice' gets printed on the output screen.

Answered By

6 Likes


Related Questions