Menu
Topics Index
...
`


Control Statements > Selection Statements >
Siva Nookala - 12 Apr 2016
Although if-else and switch are multi-way branch statements, they are not completely same.

  • switch can be used only for a specific value and can not be used for range of values or for conditions involving multiple variables. e.g., for switch the values should be 1 or 2 or 3 etc, when we use if we could use conditions like greater than 1 and less than 15 etc.
  • In switch we can execute multiple blocks for one value, when we remove break statement. i.e. use fall-through. Writing the below program using if statement is difficult will have duplicate code.
char letter = 'C';

if(letter == 'A' || letter == 'E')
{
    System.out.println("This is an vowel.");
    System.out.println("This is an alphabet.");
}
else if(letter == 'B' || letter == 'C' || letter == 'D')
{
    System.out.println("This is an alphabet.");
}
else if(letter == '@' || letter == '#')
{
    System.out.println("This is a special character.");
}
Same code using switch statement.
char letter = 'C';
switch(letter)
{
    case 'A':
    case 'E':
        System.out.println("This is an vowel.");
        // FALL - THROUGH, NO BREAK HERE
    case 'B':
    case 'C':
    case 'D':
        System.out.println("This is an alphabet.");
        break;
    case '@':
    case '#':
        System.out.println("This is a special character.");
        break;
}
  • switch is faster and simpler than if in some cases as shown below
if( direction == 'E' )
    System.out.println("East");
else if( direction == 'W' )
    System.out.println("West");
else if( direction == 'S' )
    System.out.println("South");
else if( direction == 'N' )
    System.out.println("North");
else
    System.out.println("Unknown direction");
The above if-else-if ladder is slower and complex than equivalent switch as shown below.
switch( direction )
{
    case 'E':
        System.out.println("East");
        break;
    case 'W':
        System.out.println("West");
        break;
    case 'S':
        System.out.println("South");
        break;
    case 'N':
        System.out.println("North");
        break;
    default:
        System.out.println("Unknown direction");
        break;
}

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App