Page 177 - Cs_withBlue_J_C11_Flipbook
P. 177

For example,

                    switch(ch)
                    {
                        case 1: System.out.println(5+6);
                        case 2: System.out.println(5-4);
                            break;
                        case 3: System.out.println(5*4);
                        default: System.out.println(5.0/6.0);
                    }
                 Here, if case 1 is selected, then both case 1 and case 2 will be executed. Hence,  the result will be:
                               11

                               1
                 And the control will exit from the switch statement as the break is encountered.
                 Similarly, if case 3 is selected, then after the execution of case 3, the default case will also be executed.


                 Need of Fall through Situation
                 Sometimes, we may need to execute two or more sequential cases together. Under such situations, if we exit from the
                 switch after executing from one case, then the program snippet will not provide the desired result.

                 For example,
                    public static void main()
                    {
                       Scanner sc= new Scanner(System.in);
                        char ch;
                        System.out.println("Enter an alphabet:");
                        ch=sc.next().charAt(0);
                        switch(ch)
                        {
                            case 'A':
                            case 'a': System.out.println("It is the first character of English alphabet");
                                  break;

                            case 'Z':
                            case 'z': System.out.println("It is the last character of English alphabet");
                                  break;

                            default: System.out.println("It is the middle character of English alphabet");
                        }
                    }
                 In the above program snippet, if ch is either ‘A’ or ‘a’, then the respective message will be printed. If “break” was used
                 in each case, then the message is to be written in all cases.

                 Nested switch case
                 When a switch case is used inside another switch case, then it is known as a nested switch case.
                 For example,

                    import java.util.*;
                    class nestedswitch
                    {

                                                                                                                       175
                                                                                                 Statements and Scope  175
   172   173   174   175   176   177   178   179   180   181   182