What is switch statement
A switch
statement in java is a decision making statement in which one or more block of statements are executed according to a matching condition.
It may be considered as an alternative to if-else
statement.
A switch
statement is followed by one or more case
statements, hence it is also called switch-case
statement.
The most common application of this construct is in creating menu-driven applications where a user selects an option and program performs the action as per his choice.
The expression after the
switch
statement should be enclosed between parenthesis that should result in some value.The switch statement expression should evaluate to a
char
, byte
, short
, int
.Starting java 6, it can also be an enum and from java 7, it can also be a String.
It is not permitted to use expressions which result in values of
long
, float
and double
type in switch
statement.
Each case
statement should be followed by a value.
case
statement may also be followed by an expression but it should result in a value.
Either way, the value followed by the case
statement should be a compile time constant.
Compile time constant means that it should be a constant or a final variable whose value cannot be changed.
The expression of case
should be followed by a semi-colon.
Example,
int v = 5; final int x; switch(v) { case x: // statements for this case block case 3: // statements for this case block }
In the above snippet, switch
statement is followed by a variable with some value.
It may also be an expression such as x + y
or a method call such as getCondition()
provided it returns a value of permissible data type.
Each case
statement is also followed by a value. Remember that this value should be a constant at compile time.
Thus, if you make the variable x
as non-final, then it will be a compiler error!
Secondly, it is not possible to use relational operators such as lesser than(<
) or greater than(>
) in case
statements.
It is not allowed to have more than 1 case
statements with the same value and will be a compiler error.
This is because it will confuse the compiler as to which block to execute for a given value.
Therefore, it is illegal to have below code.
int x = 0; switch(x) { case 0: // statements case 0: // COMPILER ERROR // statements case 1: // statements }
switch statement control flow
During execution, the value of expression written in switch
is calculated and it is matched with the value of each case
statement starting from the top.
The first case
statement whose value matches with the value of switch
expression is executed.
int v = 3; final int x = 0; switch(v) { case x: System.out.println("0"); case 3: System.out.println("3"); }
This switch-case
when executed will print 3
since this is the case
whose value matches with the value of switch
expression.
break statement in case
Each case
statement may optionally end with a break statement.
As stated above, when executing a switch-case
, the first case
statement with its value matching with switch
expression is executed.
If the matching case
does not end with a break
, then all subsequent case
statements after the first matching case statement are executed.
Example,
int v = 3; final int x = 0; int y = 7; switch(v) { case x: System.out.println("0"); case 3: System.out.println("3"); case 5: System.out.println("5"); case y: System.out.println("7"); }
Above example will print
3
5
7
since all the case
statements after the first case
matching the switch expression are executed. That is obviously not always desired.
To prevent such condition, end each case
with a break
so that only the matching case
statement is executed.
int v = 3; final int x = 0; int y = 7; switch(v) { case x: System.out.println("0"); break; case 3: System.out.println("3"); break; case 5: System.out.println("5"); break; case y: System.out.println("7"); break; }
This example will only print 3
because the switch-case
will terminate after the first case
execution.
Also note that the break
in last case may be omitted since there is no case
block to execute after the last one.
default statement in switch
It might happen that there is no case
statement whose value matches with the switch
expression value and you might want to take some fixed action in such scenarios such as printing an error message.
switch
statement provides a default case
which is executed when the value of any case
statement does not match with the switch
expression.
Suppose a program which displays some menu and asks user to input a choice but the user inputs some invalid value which does not match with any case
statement value.
In such scenario, default
case becomes very handy.
The default
case consists of a default keyword in place of case
and is not followed by any value. Example,
int v = 10; final int x = 0; int y = 7; switch(v) { case x: System.out.println("0"); break; case 3: System.out.println("3"); break; case 5: System.out.println("5"); break; case y: System.out.println("7"); break; default: System.out.println("No matching case"); }
In the above example, the default
statement will be executed since no case
statements has a matching value with switch
expression.
Remember that the default case
should always be the last statement in a switch-case
construct.
There will be no compiler error if you place it in the middle but then, it will be always executed and all the case
statements after it will also be executed if it does not end with break
.
Since it should be the last statement, it is not required to end it with break
.
else
block in if-else
statement which is executed when no if condition is satisfied.Multiple case blocks with same statements
A switch
statement may have more than 1 case
with different values but same set of statements.
It is like having a logical OR condition where for more than 1 values, same set of statements need to be executed. Example,
String day = ""; switch(day) { case "Saturday": case "Sunday": System.out.println("Holiday"); default: System.out.println("Working day"); }
Note that above example uses a String data type in switch
expression and case
statements.
This is possible only if you are using java 7 and above.
Nested switch statement
A switch
statement used inside another switch
statement is called nested switch.
A nested switch will be placed inside a case
statement and is required when two or more conditions need to be matched.
As stated earlier, case
statements should be compile time constants. As such, they are not allowed to contain relational and logical operators such as &&
.
The only way to achieve more than one conditions(or logical AND) is using a nested switch. Example,
System.out.println("1. Burger, 2. Pizza, 3. Sandwich"); int input = 0; // read user input switch (input) { case 1: System.out.println("Burger is ready"); break; case 2: System.out.println("Enter the type of topping"); System.out.println("1. Extra cheese, 2. Extra chicken, 3. Extra veggies"); // read user input again switch (input) { case 1: System.out.println("Extra cheese pizza!!"); break; case 2: System.out.println("Extra chicken!!"); break; case 3: System.out.println("Extra veggies!!"); break; } case 3: System.out.println("Sandwich"); break; default: System.out.println("Invalid food option!!"); }
Above switch-case
example shows a menu driven program where the user is presented with 3 food options.
If he chooses the 2nd option, then add-on options for that item are displayed.
Summing up
Following are the important bullet points that conclude this article.
- A
switch
statement should be followed by an expression which must return a value.
Value types supported arebyte
,short
,int
,char
,enum
(from java 6) andString
(from java 7). - Value in
case
statement should be a compile time constant. - Data types of values of
case
statements should match with that of theswitch
expression. case
block may consist of more than statements.- Statements of the
case
block may or may not be enclosed between curly braces. - More than one case statements can not have same values.
- Variables defined in a
case
block are not visible outside of that block. - Relational and logical operators are not allowed in
case
statements. case
statements are executed from top to bottom and the first case statement whose value matches with that ofswitch
expression is executed.case
statements may end with an optionalbreak
statement.- If there is no
break
statement, then allcase
statements after the first matchingcase
are also executed. - A
default
case is written usingdefault
keyword. It is executed when there is no matching case. default
case is optional and should be placed at the end ofswitch
though it is not mandatory to do so.- To achieve a logical OR condition, more than 1 case statements with different values may be written where only one case statement(last one out of those to be matched) shall have statements to execute.
- A switch statement inside another
switch
statement is called nested switch.
They are primarily used to achieve a logical AND condition in a case statement.
Hope this article clarified the concept of switch-case statement in java along with its different rules and examples. Hit the clap below to like it.