Page 153 - computer science (868) class 11
P. 153

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
                    {

                                                                                                                       151
                                                                                                 Statements and Scope  151
   148   149   150   151   152   153   154   155   156   157   158