switch statement in Java
A java switch statement is an alternative to a neste if else if else .... structure. Instead of checking the value of an expression at each if statement, we use a switch statemet to check it once and then jump to of of the labels that matches its value. Let us a take a look at the following example that attempts to print number of days in a month of a year.
|
If you compile and run, you get the following output
C:\Program Files\Java\jdk1.7.0_17\bin>java switch1 Number of days in month 3 is 31 |
Let us formally define a switch contruct.
|
The variable variable_to_test that we want to check resides between the round brackets of switch. For every value that we want to check, we use the keyword case. You then have the value you want to check for:
case value:
After case value comes a colon. You then put what you want to happen if the value matches. This is your code that you want executed. The keyword break is needed to break out of each case of the switch statement.
The default value at the end is optional. It can be included if there are other values that can be held in your variable but that you haven't checked for elsewhere in the switch statement.
Special Considerations
1. If you do not include a break statement, the program continues to execute the statements next to it. It can be a bug or a feature depending upon how you use it. For example, consider the following example where we missed the break statement from case 18.
|
You get the following output
You are 18 years old You are 18 years old |
You get program first transfers the control to case 18 and executes the statement
System.out.println("You are "+ age +" years old " );
Since there is no break statement, it continues to execute the statement(s) next to case 19, and the statement is printed again.
The omission of the break statement can be used favorably. Consider the number of days in a month example where use the absence of break statement favorably.
|
You get the following output
Number of days in month 6 is 30 |
The value of the variable monthnumber transfers the control to
case 6:
There are no statements to execute and since, there is no break statement, the flow continues to execute the next case statement which is case 9:. There is no statement to execute in case 9 as well and the control contines to execute next case - which is case 11. It assigns 30 to numberofdays 30 and the control breaks.
See how the absence of break has been used favorably.
Using default to our advantage
In the number of days in a month example, we can simplify it even more by making use of the deafault. Assuming that the variable monthnumber always takes a valid value between 1 ( corresponding to January) and 12 ( corresponding to December), we can simplify the program as follows.
|