- The expression must be of type
- 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
statements. Those are value1
. If the value matches with value1
is executed, if it matches value2
is executed. If it matches none of the values, then the statement3
which is under
section is executed.
It is not necessary to have
statement for every
. When value of expression
does not match any of the values and their is no
section, then no statement is executed.
It is necessary to put a
statement after every
block if we want to stop the execution. If there is no
it continues to execute the other statements present in the
statement. This is called fall-through.
public static void main(String arg)
char direction = 'S';
switch( direction )
System.out.println("East"); // LINE A
System.out.println("West"); // LINE B
System.out.println("South"); // LINE C
System.out.println("North"); // LINE D
System.out.println("Unknown Direction"); // LINE E
System.out.println("After switch"); // LINE F
Since the value of
'S', it is compared with various values
'S'. Since it matches
LINE C is executed. If the direction was
'N' instead of
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
- Remove the
break statement after
LINE C. When you remove the
break, the control does not break after
LINE C and executes
LINE Dhence printing North and then it breaks since it encounters
LINE D. This is also called fall-through.
- Try putting duplicate case values, by changing
'W' also to
case 'W' in
LINE B to case
- Try putting ascii code of
'S' which is
83 instead of char
case 83: instead of
- Move the
default block above and see that
default need not be the last case and can be present any where.