1
0

Switch Case in Java

Unlike if-then and if-then-else, the switch statement allows for any number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with a few special classes that “wrap” certain primitive types: Character, Byte, Short, and Integer (discussed in Simple Data Objects).

The switch statement can replace the if-else-if construct effectively and reduce the number of braces. This option provides a better way to write neat and understandable code. The syntax of the switch statement is:

switch ( <Expression> )
{
    case val_1:
        <statement-1>;
        ........
        break;
    case val_2:
        <statement-2>;
        ........
        break;
    ....
    default:
        <default statement>;
}

Important points about the switch case statement:

  • Switch expression must result in an integer or character value.
  • The case value must be followed by a colon (:).
  • Character case value must be written in a single quote as ‘a’.
  • The default case is optional. It can be placed anywhere in the switch case construct but is executed only if no case match occurs.
  • All the statements up to break; or till the end of the switch are executed from the matching case.
  • The statement of the case need not be placed in braces {}.

The following program, SwitchDemo, declares an int-type variable named month whose value represents a month of the year.

The program displays the name of the month, based on the value of the month, using the switch statement.

class SwitchDemo
{
    public static void main(String args[])
    {
        int month = 8;
        switch(month)
        {
            case 1:
                System.out.println("January");
                break;
            case 2:
                System.out.println("February");
                break;
            case 3:
                System.out.println("March");
                break;
            case 4:
                System.out.println("April");
                break;
            case 5:
                System.out.println("May");
                break;
            case 6:
                System.out.println("June");
                break;
            case 7:
                System.out.println("July");
                break;
            case 8:
                System.out.println("August");
                break;
            case 9:
                System.out.println("September");
                break;
            case 10:
                System.out.println("October");
                break;
            case 11:
                System.out.println("November");
                break;
            case 12:
                System.out.println("December");
                break;
            default:
                System.out.println("Invalid Month");
                break;
        }
    }
}

In this case, “August” is printed to standard output.

The body of a switch statement is known as a switch block. Any statement immediately contained by the switch block may be labeled with one or more case or default labels. The switch statement evaluates its expression and executes the appropriate case.

Of course, you could also implement the same thing with if-else statements:

int month = 8;
if (month == 1)
{
    System.out.println("January");
}
else
{
    if(month == 2)
    {
        System.out.println("February");
    }
    .... // and so on
}

Deciding whether to use if-else statements or switch statements is sometimes a judgment call. You can decide which one to use based on readability and other factors. An if-else statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer or character value.

Another point of interest is the break statement after each case. Each break statement terminates the enclosing switch statement. Control flow continues with the first statement following the switch block. The break statements are necessary because without them, case statements fall through; that is, without an explicit break, control will flow sequentially through subsequent case statements starting from the matching case. The following program, SwitchDemo2, illustrates why it might be useful to have case statements fall through:

Program to display the number of days in a month:

class SwitchDemo2
{
    public static void main(String[] args)
    {
        int month = 2;
        int year = 2000;
        int numDays = 0;
        switch (month)
        {
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                numDays = 31;
                break;
            case 4:
            case 6:
            case 9:
            case 11:
                numDays = 30;
                break;
            case 2:
                if(((year%4 == 0) && !(year%100 == 0)) || (year%400 == 0))
                    numDays = 29;
                else
                    numDays = 28;
                break;
            default:
                System.out.println("Invalid month.");
                break; // optional
        }
        System.out.println("Number of Days = " + numDays);
    }
}

Output:

Number of Days = 29

Technically, the final break is not required because flow would fall out of the switch statement anyway. However, we recommend using a break so that modifying the code is easier and less error-prone. The default section handles all values that aren’t explicitly handled by one of the case sections.

Looping statements are used to repeatedly execute a group of statements until a certain condition remains satisfied. These statements are also called Iteration statements, as the control iterates through a group of statements a number of times. Java language provides three looping statements namely for, while, and do-while as described in the next article.

Leave a Reply