Switch Case in Java

Switch Case In Java

A switch case is used to execute the code, among many alternatives. You can use a switch case as an alternative of if-elseif condition.

Switch Case Syntax

switch(expression) {
    case value1:
        statement1;
        break;
    case value2:
        statement2;
        break;
    case value3:
        statement3;
        break;
    default:
        default statement;
}
  • Here, switch expression runs once.
  • The value of an expression is compared with the value of each case.
  • If the expression matches with value 1, statement1 is executed. Similarly, statement2 is executed if the expression matches with value 2 and so on.
  • If there is no match default statement is executed.
Info

Note: Always add break; after each case statement. It breaks out of the switch block when the match is found. For the default case, break; is not necessary.

Example of switch case to print no of day by number.

Here if noOfDays contain a value 1, then it will print Sunday, if noOfDays have a value 7, it will print Saturday.

public class Main {
    public static void main(String[] args) {
        int noOfDays = 2;
        switch (noOfDays) {
            case 1:
                System.out.println("The day is sunday.");
                break;
            case 2:
                System.out.println("The day is monday.");
                break;
            case 3:
                System.out.println("The day is tuesday.");
                break;
            case 4:
                System.out.println("The day is wednesday.");
                break;
            case 5:
                System.out.println("The day is thrusday.");
                break;
            case 6:
                System.out.println("The day is friday.");
                break;
            case 7:
                System.out.println("The day is saturday.");
                break;
            default:
                System.out.println("Invalid option given!!!");
        }
    }
}
Show Output