CODE
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
}
}
South
After switch
Since 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.
default
section and initialize the direction
to 'M'
.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.'W'
also to 'S'
. case 'W'
in LINE B
to case 'S'
.'S'
which is 83
instead of char 'S'
i.e. case 83:
instead of case 'S':
.default
block above and see that default
need not be the last case and can be present any where.