In Java, a switch
statement is used to transfer control to a particular block of code, based on the value of the variable being tested.
Note: Switch statements are an efficient alternative for if-else statements.
The switch
is passed a variable, the value of which is compared with each case value. If there is a match, the corresponding block of code is executed.
The general syntax of the switch
statement is as follows:
switch (variable){case value_1://codecase value_2://codedefault://code}
The variable passed to the switch
can be of following types:
Consider the following example to get a better idea of how the switch
statement works.
If you want to write a piece of code which prints the weather forecast corresponding to the given input.
class HelloWorld {public static void main( String args[] ) {int weather = 2;//passing variable to the switchswitch (weather){//comparing value of variable against each casecase 0:System.out.println("It is Sunny today!");break;case 1:System.out.println("It is Raining today!");break;case 2:System.out.println("It is Cloudy today!");break;//optionaldefault:System.out.println("Invalid Input!");}}}
Note:
Duplicate case values are not allowed.
The value of a case must be the same data type as the variable in the switch.
Adding the
default
case is optional but handling unexpected input is considered a good programming practice.
If the break
statement is not used, all cases after the correct case are executed.
Execute the following code to see what happens if we eliminate the break statement from each code block:
class HelloWorld {public static void main( String args[] ) {int weather = 0;//passing variable to the switchswitch (weather){//comparing value of variable against each casecase 0:System.out.println("It is Sunny today!");case 1:System.out.println("It is Raining today!");case 2:System.out.println("It is Cloudy today!");//optionaldefault:System.out.println("Invalid Input!");}}}