What is a switch case?

The switch case statement allows us to tests the equality of a variable against multiple values, where each value is a different case, it is similar to the ladder if-else statement. In simple words, the switch case statement is used, when we have multiple options and for each option, we want to perform a different task.

Flow diagram

Syntax

switch(<expression>) {

   case <value 1>:
      // Code to execute, when <expression> is equals to <value 1>
      break; // optional
   
   case <value 2>:
      // Code to execute, when <expression> is equals to <value 2>
      break; // optional
   
   case <value N>:
      // Code to execute, when <expression> is equals to <value N>
      break; // optional
   
   default : // A default optional case
      // Code to execute, when <expression> is not matched to any value
}

Switch expression

You can pass any of the following values in a switch expression –

  1. Primitive data-types – (byte, short, char, int)
  2. Non-primitive data-types (Byte, Short, Character, Integer)
  3. The String class
  4. Enumerated type – (Java enum)

Case expression

The case expression value’s type should be exactly similar to the switch expression type, means if you are passing integer data in switch expression then you are only allowed to pass an integer value in case expression. The case expression can only have a constant value or a variable declared as final.

Example

The following switch-case example program prints weekday’s name according to given weekday’s number –

import java.util.Scanner;

public class SwitchCaseExample {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter a weekday number :");

        int weekday = scanner.nextInt();

        switch (weekday) {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
            case 6:
                System.out.println("Saturday");
                break;
            case 7:
                System.out.println("Sunday");
                break;
            default:
                System.out.println("Invalid");
                break;
        }
    }
}

The break statement after each println() statement is optional, it breaks the further case tests once a case satisfies the condition.