The Switch statement
Switch
Sometimes it becomes cumbersome to write lengthy
programs using if and if-else statements. To avoid this we can use Switch statements
in Java. The switch statement is used to select multiple alternative execution
paths. This means it allows any number of possible execution paths. However,
this execution depends on the value of a variable or expression. The switch
statement in Java is the best way to test a single expression against a series
of possible values and executing the code.
Here is the general form of switch statement:
switch (expression){
case 1:
code block1
case 2:
code block2
.
.
.
default:
code default;
}
The expression to the switch must be of a type byte, short, char, or int.
Then there is a code block following the switch statement that comprises of
multiple case statements and an optional default statement.
The execution of the switch statement takes place by comparing the value of the
expression with each of the constants. The comparison of the values of the expression with each of the constants
occurs after the case statements. Otherwise, the statements after the default
statement will be executed.
Now, to terminate a statement following a switch
statement use break statement within the code block. However, its an
optional statement. The break statement is used to make the computer jump to the
end of the switch statement. Remember, if we won't use break statement the
computer will go ahead to execute the statements associated with the next case
after executing the first statement.
Here is an example which will help you to understand more easily:
switch (P {
// assume P is an integer variable case 1: System.out.println("The number is 1."); break; case 2: case 4: case 8: System.out.println("The number is 2, 4, or 8."); System.out.println("(That's a power of 2!)"); break; case 3: case 6: case 9: System.out.println("The number is 3, 6, or 9."); System.out.println("(That's a multiple of 3!)"); break; case 5: System.out.println("The number is 5."); break; default: System.out.println("The number is 7,"); System.out.println(" or is outside the range 1 to 9."); } |
For example the following program Switch, declares an int named week whose value represents a day out of the week. The program displays the name of the day, based on the value of week, using the switch statement.
class Switch{
|
Output:
C:\javac>javac Switch.java C:\javac>java Switch friday |
In this case, "friday" is printed to standard output.
One other point to note here is that the body of a switch statement is known as
a switch block. The appropriate case gets executed when the switch
statement evaluates its expression.