Page 176 - Cs_withBlue_J_C11_Flipbook
P. 176

case '+' :   System.out.println(" Sum : "+(a+b));
                               break;
                      case '-' :   System.out.println(" Difference : "+(a-b));
                               break;
                      case '*' :   System.out.println(" Product : "+(a*b));
                               break;
                      case '/' :   System.out.println(" Quotient : "+(a/b));
                               break;
                      default:       System.out.println("You have entered wrong choice");
                  }
                   Depending on the operator, the respective case is called. If “ch” does not match any case, default is executed and
                  the message “You have entered wrong choice” will be printed.

              3.    // The following program snippet uses String data type
                  import java.util.*;
                  class switchstring
                  {
                      public static void main()
                      {
                          Scanner sc= new Scanner(System.in);
                          int a=6, b=3;
                          String ch=sc.next();
                          switch(ch)
                          {
                              case "ADD" :  System.out.println(" Sum : "+(a+b));
                                  break;
                              case "SUB" :  System.out.println(" Difference : "+(a-b));
                                  break;
                              case "MUL" :  System.out.println(" Product : "+(a*b));
                                  break;
                              case "DIV" :  System.out.println(" Quotient : "+(a/b));
                                  break;
                              default:          System.out.println("You have entered wrong choice");
                          }
                      }
                  }
                   Depending on the operator, the respective case is called. If “ch” does not match any case, default is executed and
                  the message “You have entered wrong choice” will be printed.

                      Note:  The data type of the expression or the variable provided in a switch statement can be int, char or
                      string. We cannot use real and boolean data types.


              Fall through
              The break statement in a switch case construct represents the exit from the selected case. If we do not provide a break
              statement after a case, it will not exit from the case and executes the rest of the cases. This situation of moving of
              control from one case to another case in the absence of a “break” statement is known as Fall Through.




                174174  Touchpad Computer Science-XI
   171   172   173   174   175   176   177   178   179   180   181