Switch case statement in Java

A switch statement is a conditional statement that tests against multiple cases and displays one or multiple outputs based on the matching circumstances. Unlike if-then and if-then-else statements, the switch statement can work with byteshortchar, and int primitive data types. It also works with enum types (discussed in Java Enum), the String class, and a few wrapper classes: CharacterByteShort, and Integer.

Important Rules

  • Only constants or literals are allowed in case
  • Duplicate values in the case are not allowed
  • default statement is optional, and it can appear anywhere in switch body not necessarily in the end
  • break statement is optional, and if not used, execution will move to the next statement.
  • Make sure that the expression in any switch statement is not null to prevent a NullPointerException from being thrown.

Syntax of a switch statement

switch(expression)
{
   case value1 :
      <<CODE_TO_EXECUTE>>
      break;

   default : 
      <<CODE_TO_EXECUTE>>   

   case value2 :
      <<CODE_TO_EXECUTE>>
}

Example code of Switch statement

public class switch_statement {

    public static void main(String[] args) {

        int weekday = 10;
        String weekdayString;
        // switch statement with int data type
        switch (weekday) {
            case 1:
                weekdayString = "Sunday";
                break;
            case 2:
                weekdayString = "Monday";
                break;
// default statement can be anywhere. Not necessarily in the end only
            default:
                weekdayString = "Not a weekday";
                break;
            case 3:
                weekdayString = "Tuesday";
                break;
            case 4:
                weekdayString = "Wednesday";
                break;
            case 5:
                weekdayString = "Thursday";
                break;
            case 6:
                weekdayString = "Friday";
                break;
            case 7:
                weekdayString = "Saturday";
                // break is not required for last case
        }
        System.out.println(weekdayString);
    }
}

Use of break statement

Though the break statement is optional. It plays an important role in controlling the execution flow. If we don’t use it, execution will continue to the next case. Sometimes it is desirable to have multiple cases without break statements between them. Especially when you want to perform the same action for more than one case.

public class switch_statement {

    public static void main(String[] args) {
        boolean isWeekend = false;
        int weekday = 5;
        switch (weekday) {
            /*
             * Two cases can be combined in different ways. 
             * Either by writing case 1,7 
             * or 
             * case 1:
             * case 2:
             * Both are valid. Though i prefer first option. :)
             */
            case 1, 7:
                isWeekend = true;
                break;
            case 2:
            case 3:
            case 4:
            case 5:
            case 6:
                isWeekend = false;
        }
        System.out.println("Is it Weekend ? " + isWeekend);
    }
}

Java 7 switch case string

In Java SE 7 and later, you can use a String object in the switch statement’s expression. Please note that String.equals() method is used to compare the switch expression with expression associated with each case label. There is no direct way of comparing the string ignoring case. To do so, follow below practice. Please see below example

public class switch_statement {

    public static void main(String[] args) {
        String weekdayString = "Friday";
        int weekdayInt;

        switch (weekdayString.toUpperCase()) {
            case "SUNDAY":
                weekdayInt = 1;
                break;
            case "MONDAY":
                weekdayInt = 2;
                break;
            default:
                weekdayInt = 0;
                break;
            case "TUESDAY":
                weekdayInt = 3;
                break;
            case "WEDNESDAY":
                weekdayInt = 4;
                break;
            case "THURSDAY":
                weekdayInt = 5;
                break;
            case "FRIDAY":
                weekdayInt = 6;
                break;
            case "SATURDAY":
                weekdayInt = 7;
        }
        System.out.println(weekdayInt + " DAY OF THE WEEK");
    }
}

Java 12 switch statement

In Java 12, an extended switch statement has been added so that it can be used as either a statement or an expression. Before Java 12, switch was only used as a statement to control the flow. After Java 12, switch can be used as expression too, which means now switch can be evaluated to get the exact value like tertiary operator.

This change not only simplifies the coding but also prepares the way for the use of pattern matching in the switch. Statement and expression form can use either traditional caselabels (e.g. case 1:) (with fall through) or simplified case labels ( e.g. case -> 1) (no fall through). 

With the new extended switch statement, we no longer use a colon, but arrow syntax from the lambda expression. Also, the break keyword is not required anymore and the fall-through case will not happen. Whatever is on the right side of -> will get executed. If you want to evaluate multiple statements at the same time in a case you can do this with blocks {}.

We can utilize the extended switch statement to re-write the above code.

public class switch_statement {

    public static void main(String[] args) {
        int weekday = 1;
        <em>switchExtendedVersion</em>(weekday);
    }

    private static void switchExtendedVersion(int weekday) {
// Switch expression is used to assign the result value to local variable
        boolean isWeekend = switch (weekday) {
            case 1, 7 -> {
                System.<em>out</em>.println("Multiple statement evaluation test");
                break true;
            }
            /*
             * Here default is mandated by compiler.
             * As 'switch' expression needs to cover all possible values.
             */
            default -> throw new IllegalStateException("Unexpected value: " + weekday);
            case 2, 3, 4, 5, 6 -> false;
            case 9 -> true;
        };
        System.<em>out</em>.println("Is it Weekend ? " + isWeekend);
    }
}

Here default case is mandated by the java compiler as an extended switch statement is supposed to cover all possible values. For the old switch statement default case is purely optional.

Java 12 introduces switch expressions as a preview language feature. That means it can change over the next few releases. And this feature needs to enabled at compile time and run time, with the new command line option –enable-preview…

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.