Computer Applications

What is a fall through? Give an example.

Java Conditional Stmts

14 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. For example, consider the below program:


public class FallThroughExample {
    public static void main(String args[]) {
        int number = 1;
        switch(number) {
            case 0:
                System.out.println("Value of number is zero");
            case 1:
                System.out.println("Value of number is one");
            case 2:
                System.out.println("Value of number is two");
            default:
                System.out.println("Value of number is greater than two");
        }
        System.out.println("End of switch");
    }
}

Its output when executed will be:

Value of number is one
Value of number is two
Value of number is greater than two
End of switch

Answered By

5 Likes


Related Questions