Page 238 - IT-802_class_12
P. 238

3.4.3 The Switch Statement

        The switch statement is used to execute a block of code matching one value out of many possible values. The syntax
        of the Java switch statement is as follows:
        switch (expression)

        { case constant_1 : statements;
        break;
        case constant_2 : statements;
        break;

        default : statements;
        break;
        }
        Within the switch statement, as you can see, there can be many case statements. The expression is compared with
        the  constants  in  each  case  group  and  the  matching  case  group  is  executed.  If  the  expression  evaluates  to  some
        constant=constant_1, the statements in the case group constant_1 are executed. Similarly, if the expression evaluates
        to constant_2, the statements in the case group constant_2 are executed. The break statement after each case group
        terminates the switch and causes execution to continue to the statements after the switch. If there is no match for the
        expression with any case group, the statements in the default part are executed. The expression in the switch statement
        must evaluate to byte, short, int, or char. The program code below demonstrates usage of the switch statement.

        public class SwitchDemo
        {
        public static void main (String[ ] args)
        {

        int today = 5; String day = “”;
        switch (today)
        {
        case 1: day = “monday”;

        break;
        case 2: day = “Tuesday”;
        break;
        case 3: day = “Wednesday”;

        break;
          236   Touchpad Information Technology-XII
   233   234   235   236   237   238   239   240   241   242   243