Tuesday, October 20, 2015

Switch Statement used in JAVA

Java provides a multiple-branch selection statement known as switch. This selection statement successively tests the value of an expression against a list of integer or character constants. When a match is found, the statements associated with that constants are executed.

The syntax of switch statement is as follows:

switch (expression)
{
        case constant1 : statement sequence 1;
break;
        case constant2 : statement sequence 1;
break;
        case constant3 : statement sequence 1;
break;
        …….
        case constantn-1 : statement sequence 1;
break;
        [default : statement sequence n];
}

The expression is evaluated and its values are matched against the values of the constants specified in the case statements. When a match is found, the statement sequence associated with that case is executed until the break statement or the end of switch statement is reached. The default statement gets executed when no match is found. If the control flows to the next case below the matching case, in the absence of break, this is called fall through. The default statement is optional and, if it is missing, no action takes place if all matches fail.

If you do not give break after each case, then java will start executing the statements from matching, case and keep on executing statements for following cases as well until either a break statement is found or switch statement’s end is encounted. If the control flows to the next case below the matching case, in the absence of break, this is called fall through.

A case statement cannot exist by itself, outside of a switch. The break statement, used under switch, is one of java jump statements. (You’ll learn more about it later in the chapter.) When a break statement is encountered in a switch statement, program execution jumps to the line of code following the switch statement i.e. outside the body of switch statement.

Following example will show a switch statement:

switch (dow)
{
        case 1 : ans = “Sunday”;
         break;
        case 2 : ans = “Monday”;
        break;
        case 3 : ans = “Tuesday”;
        break;
        case 4 : ans = “Wednesday”;
        break;
        case 5 : ans = “Thursday”;
        break;
        case 6 : ans = “Friday”;
        break;
        case 7 : ans = “Saturday”;
        break;
        default : ans = “Wrong day number”;
}

No comments:

Post a Comment