Menu
Topics Index
...
`

Print Direction - Java Example Program


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
    
    }
}
OUTPUT

South
After switch

DESCRIPTION

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.

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 Dhence 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.

© meritcampus 2019

All Rights Reserved.

Open In App