Page 80 - iprime_V2.2_class8
P. 80

For example:

                  public class IfElseIfStatement
                  {
                         public static void main(char ch)
                         {
                                char C = ch;
                                System.out.println("Entered character is: " + ch);
                                if(C == 'W')
                                {
                                       System.out.println("Enjoy Winter");
                                }
                                else if(C == 'R')
                                {
                                       System.out.println("Enjoy Rainy");
                                }
                                else if (C == 'S')
                                {
                                       System.out.println("Enjoy Summer");
                                }
                                else
                                {
                                       System.out.println("Invalid Character");
                                }
                         }
                  }
                  Run  this  program  four  times  with  the  inputs  'W',

                  'R',  'S',  and  'T'.  You  will  see  the  output  as  “Enjoy
                  Winter”, “Enjoy Rainy”, “Enjoy Summer” and “Invalid
                  Character”  respectively.  This is because  each  time
                  the  condition  is checked  against  the  conditional
                  expressions  written  after  the  'if'  and  'else...if'
                  keywords, it executes the statements written inside
                  the block where a perfect match is found.
                  The Switch Statement                                                         Output

                  Using the long 'if...else...if' ladder becomes tedious and makes the code more complex. The switch

                  statement is used as substitute for the 'if...else...if' ladder. It is a multi-way branch statement that
                  allows a variable to be checked for equality with a list of values. Each value in the list is called a case.
                  The 'case' keyword is used with the 'switch' keyword to define a case. The switch statement also
                  uses 'break' and 'default' keywords. The 'break' keyword is used to stop the execution of 'switch'
                  statement when a matched case is found. On the other hand, 'default' keyword is used to specify
                  some code to be executed if there is no matched case found.


                  78     iPRIME (Ver. 2.2)–VIII
   75   76   77   78   79   80   81   82   83   84   85