Page 196 - ComputerScience_Class_11
P. 196

For example,
                              Write a Java program that demonstrates the concept of fall through in a switch statement.
                Program 2
                              The program should evaluate the value of a variable day and print the corresponding day of
                              the week.
                              •  If the value of day is 1, print "Monday".
                              •  If the value of day is 2, print "Tuesday".
                              •  If the value of day is 3, print "Wednesday" and break the switch statement.
                              •  If the value of day is 4, print "Thursday".
                              •  If the value of day doesn't match any case, print "Invalid day".
                              •   Ensure that there is no break statement after the cases for 1 and 2, to demonstrate fall
                                through behaviour.

                1       public class FallThroughExample {
                2           public static void main(String[] args) {
                3               int day = 2;

                4               switch (day) {
                5                   case 1:
                6                       System.out.println("Monday");

                7                       // Fall through, no break
                8                   case 2:
                9                       System.out.println("Tuesday");

                10                      // Fall through, no break
                11                  case 3:
                12                      System.out.println("Wednesday");

                13                      break;
                14                  case 4:
                15                      System.out.println("Thursday");

                16                      break;
                17                  default:

                18                      System.out.println("Invalid day");
                19              }
                20          }
                21      }

              The output of the preceding program is as follows:

                     BlueJ: Terminal Window - Java

                 Options

                Tuesday
                Wednesday







                  194  Touchpad Computer Science (Ver. 3.0)-XI
   191   192   193   194   195   196   197   198   199   200   201