Page 171 - CA_Blue( J )_Class9
P. 171

System.out.println(c + "is smallest number");
                    else
                        System.out.println(c + "is the largest number");
                 8.1.3 Multiple Branching Flow of Control
                 While programming in Java, you might come across scenarios where you need to choose a certain condition and
                 execute the corresponding set of statements. When such a program is executed the control moves from branch to
                 branch in order to select one branch based on a condition and execute it to  produce the desired results. This type
                 of branching is called multiple branching. Switch case statements are used in such scenarios. Let us understand
                 how to use switch case statements.


                 Switch Statement
                 In certain programming scenarios, a menu is given to the user, depending on the choices in the menu, a portion of the
                 conditional constructs will be executed. The flowchart given below shows how the control flows in such a scenario.
                 Flow Diagram of switch case:

                 Syntax:
                    switch(expression)
                    {
                        case1 value1: //Statements of block 1;
                                        break;
                        case2 value2: //Statements of block 2;
                                        break;
                        .
                        .
                        .
                        default: //Statements of block last;
                    }
                                                             Definition


                   Multiple Branching statement which allows the user to choose any one case out of the number of cases
                   provided in the code is defined as Switch Case Statement.



                 Each case value must be a constant or a literal. It cannot be a variable or an expression. The switch statement does not
                 work with floating-point types (float, double) or boolean values.
                 On the other hand, the if statement can handle any data type and more complex conditions.

                 Example:
                        char code='A';
                        switch(code)
                        {
                             case 'A': System.out.println("Manager");
                                        break;
                             case 'B': System.out.println("Team Head");
                                        break;
                             case 'C': System.out.println("Supervisor");
                                        break;



                                                                                     Conditional Constructs in Java  169
   166   167   168   169   170   171   172   173   174   175   176