switch(expression)
{
case value1:
// statement1;
break;
case value2:
// statement2;
break;
default:
// statement3;
break;
}
- The expression must be of type
byte
, short
, int
or char
.
- From JDK7, expression as
String
is also supported.
- Each value provided in case should be a literal value and variables are not allowed here.
- Duplicate case values are not allowed.
- The type of each value must be compatible with the expression.
The value of
expression is evaluated and compared with each of the values in
case
statements. Those are
value1,
value2. If the value matches with
value1 then
statement1 is executed, if it matches
value2 then
statement2 is executed. If it matches none of the values, then the
statement3 which is under
default
section is executed.
It is not necessary to have
default
statement for every
switch
. When value of
expression does not match any of the values and their is no
default
section, then no statement is executed.
It is necessary to put a
break
statement after every
case
block if we want to stop the execution. If there is no
break
it continues to execute the other statements present in the
switch
statement. This is called fall-through.
Print Direction
class PrintDirection
{
public static void main(String arg[])
{
char direction = 'S';
switch( direction )
{
case 'E':
System.out.println("East"); // LINE A
break;
case 'W':
System.out.println("West"); // LINE B
break;
case 'S':
System.out.println("South"); // LINE C
break;
case 'N':
System.out.println("North"); // LINE D
break;
default:
System.out.println("Unknown Direction"); // LINE E
break;
}
System.out.println("After switch"); // LINE F
}
}
DESCRIPTIONSince the value of direction
is 'S'
, it is compared with various values 'E'
, 'W'
, 'N'
and 'S'
. Since it matches 'S'
, LINE C
is executed. If the direction was 'N'
instead of 'S'
, then LINE D
is executed. If the direction was 'M'
, since it does not match any of the values, the LINE E
in the default
section is executed.
THINGS TO TRY
- Remove the
default
section and initialize the direction
to 'M'
.
- Remove the
break
statement after LINE C
. When you remove the break
, the control does not break after LINE C
and executes LINE D
hence printing North and then it breaks since it encounters break
after LINE D
. This is also called fall-through.
- Try putting duplicate case values, by changing
'W'
also to 'S'
. case 'W'
in LINE B
to case 'S'
.
- Try putting ascii code of
'S'
which is 83
instead of char 'S'
i.e. case 83:
instead of case 'S':
.
- Move the
default
block above and see that default
need not be the last case and can be present any where.
4-min video about switch statement in Java