Page 336 - CITS - Computer Software Application -TT
P. 336

COMPUTER SOFTWARE APPLICATION - CITS




           •  Default statement is executed when any of the case doesn’t match the value of expression. It is optional.
           •  Break statement terminates the switch block when the condition is satisfied.
              It is optional, if not used, next case is executed.
           •  While using switch statements, we must notice that the case expression will be of the same type as the
              variable. However, it will also be a constant value.
           The syntax to use the switch statement is given below.
           switch (expression){
           case value1:
           statement1;

           break;
           .
           .
           .

           case valueN:
           statementN;
           break;
           default:
           default statement;

           }
           Consider the following example to understand the flow of the switch statement.
           Student.java
           public class Student implements Cloneable {

           public static void main(String[] args) {
           int num = 2;
           switch (num){
           case 0:
           System.out.println(“number is 0”);
           break;

           case 1:
           System.out.println(“number is 1”);
           break;
           default:

           System.out.println(num);
           }
           }
           }
           Output:

           2
           While using switch statements, we must notice that the case expression will be of the same type as the variable.
           However, it will also be a constant value. The switch permits only int, string, and Enum type variables to be used.



                                                           323
                               CITS : IT&ITES - Computer Software Application - Lesson 85 - 93
   331   332   333   334   335   336   337   338   339   340   341