Page 185 - Computer science 868 Class 12
P. 185

if(var2 <= var3)
                        least_number = var2;
                        else
                        least_number = var3;
                    }

                    // Using Ternary Operator

                         int least_number = (var1 <= var2) ? ((var1 <= var3) ? var1 : var3) : ((var2 <= var3)
                        ? var2 : var3);
                 7.2.3 Switch Statement
                 The Java switch statement executes one statement from given multiple conditions or expressions. It is also known as
                 a multiple-branch selection statement. The value of the expression is compared with the value of each case. The data
                 type of the variable used in the expression can be either int or char. When a match is found, i.e., if a case is executed,
                 the corresponding statements will be executed. If no case is matched, then the default part will be executed and it will
                 exit from the switch.

                 Syntax:
                    switch(choice)
                    {
                        case value1:
                                  //statements;
                       break;   //optional
                        case value2:
                                  //statements;
                       break;   //optional
                        ......

                        default: //if no case is executed;
                    }
                 Here, ‘break’ and ‘default’ are the keywords.
                 Let us take different examples for better understanding.

                 Example 1: // Using char variable
                    class switchcase
                    {
                        public static void main(char ch)
                        {

                            switch(ch)
                              {
                                //Case statements
                                case '+': System.out.println("Addition Operator");
                                    break;
                                case '-': System.out.println("Subtraction Operator");
                                    break;
                                case '*': System.out.println("Multiplication Operator");
                                    break;
                                case '/': System.out.println("Division Operator");
                                    break;
                                default:System.out.println("No Arithmetical Operator");
                            }
                        }
                    }


                                                                                                                       183
                                                                                                 Statements and Scope  183
   180   181   182   183   184   185   186   187   188   189   190