Java switch Statement


The switch statement in Java is a control flow statement that allows you to execute one out of multiple code blocks based on the value of an expression. It is often used as an alternative to multiple if-else statements when you have a single variable to compare against multiple possible values.

The switch statement improves the readability and efficiency of your code when you need to compare a variable to several potential values.

In this guide, we'll explore the switch statement in detail, including its syntax, how it works, and provide examples of its usage.

Table of Contents

  1. What is the Java switch Statement?
  2. Syntax of the switch Statement
  3. How the switch Statement Works
  4. Java switch Statement Example
  5. Using break in switch
  6. Default Case in switch
  7. Java switch Expression (Java 12 and later)
  8. Best Practices for Using switch

What is the Java switch Statement?

The switch statement is used to evaluate an expression and match its value against one or more predefined cases. The matching case executes the corresponding block of code. If no case matches the value, an optional default case can be executed.

The switch statement provides a cleaner and more efficient way of handling multiple conditions compared to using a series of if-else statements. It is typically used when a variable can take one of several discrete values, such as an integer, character, or string.


Syntax of the switch Statement

The syntax for the switch statement is straightforward:

switch (expression) {
    case value1:
        // Code to execute if expression equals value1
        break;
    case value2:
        // Code to execute if expression equals value2
        break;
    case value3:
        // Code to execute if expression equals value3
        break;
    // More cases as needed
    default:
        // Code to execute if no case matches
}
  • expression: The expression whose value will be compared against the values of the cases.
  • case value: These are the possible values that the expression can match. Each case has an associated block of code that gets executed if the case value matches the expression.
  • break: After each case block, break is used to terminate the switch statement and prevent it from falling through to the next case.
  • default: The default case is optional. It’s executed when none of the case values match the expression.

How the switch Statement Works

When a switch statement is executed, the following steps occur:

  1. The value of the expression is evaluated.
  2. The program compares the value of the expression with each case value in the switch statement.
  3. If a match is found, the corresponding code block is executed.
  4. After the execution of a matching case, the break statement is executed to exit the switch statement. If no break is used, execution will "fall through" to the next case.
  5. If no cases match and a default block is provided, the code inside the default block will be executed.

Java switch Statement Example

Let’s explore some examples of how to use the switch statement in Java.

Example 1: Basic switch Example

Here’s a simple example using a switch statement with an integer value:

public class SwitchExample {
    public static void main(String[] args) {
        int day = 3;
        
        switch (day) {
            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;
            default:
                System.out.println("Weekend");
        }
    }
}

Explanation:

  • The switch statement checks the value of the day variable.
  • Since day is 3, the program prints "Wednesday".
  • The break statement ensures that the program exits the switch after executing the matching case.

Output:

Wednesday

Example 2: switch with String

Java allows you to use a switch statement with strings as well. Here’s an example:

public class SwitchWithString {
    public static void main(String[] args) {
        String day = "Sunday";
        
        switch (day) {
            case "Monday":
                System.out.println("Start of the work week");
                break;
            case "Friday":
                System.out.println("Almost weekend!");
                break;
            case "Sunday":
                System.out.println("Weekend!");
                break;
            default:
                System.out.println("Middle of the week");
        }
    }
}

Explanation:

  • The switch statement compares the string day with the case values.
  • Since day is "Sunday", the program prints "Weekend!".

Output:

Weekend!

Example 3: switch with Multiple Cases

You can group multiple cases in a switch statement. This allows you to run the same code block for several cases:

public class SwitchMultipleCases {
    public static void main(String[] args) {
        char grade = 'B';
        
        switch (grade) {
            case 'A':
            case 'B':
                System.out.println("Excellent");
                break;
            case 'C':
                System.out.println("Good");
                break;
            case 'D':
                System.out.println("Fair");
                break;
            default:
                System.out.println("Invalid grade");
        }
    }
}

Explanation:

  • The case 'A' and case 'B' are grouped together, meaning that both will result in the message "Excellent" being printed.
  • Since grade is 'B', the output is "Excellent".

Output:

Excellent

Using break in switch

The break statement in the switch statement is essential. It ensures that once a case is executed, the program control exits the switch. Without the break, the program will continue executing the next case (this behavior is known as fall-through).

Here’s an example to demonstrate fall-through:

public class SwitchWithoutBreak {
    public static void main(String[] args) {
        int number = 2;
        
        switch (number) {
            case 1:
                System.out.println("One");
            case 2:
                System.out.println("Two");
            case 3:
                System.out.println("Three");
            default:
                System.out.println("Invalid number");
        }
    }
}

Explanation:

  • Since there are no break statements, once case 2 is matched, the program will execute all subsequent cases until the switch block ends.
  • The output will be:
    Two
    Three
    Invalid number
    

Default Case in switch

The default case is optional but highly recommended as a fallback option. It is executed if none of the specified cases match the value of the expression.

Here’s an example:

public class SwitchWithDefault {
    public static void main(String[] args) {
        int number = 6;
        
        switch (number) {
            case 1:
                System.out.println("One");
                break;
            case 2:
                System.out.println("Two");
                break;
            default:
                System.out.println("Invalid number");
        }
    }
}

Explanation:

  • Since there is no case for the number 6, the default case is executed.

Output:

Invalid number

Java switch Expression (Java 12 and later)

From Java 12, the switch statement introduced a new switch expression. This allows you to return a value from the switch statement, making it more versatile.

Here’s an example:

public class SwitchExpression {
    public static void main(String[] args) {
        int day = 3;
        
        String result = switch (day) {
            case 1 -> "Monday";
            case 2 -> "Tuesday";
            case 3 -> "Wednesday";
            case 4 -> "Thursday";
            case 5 -> "Friday";
            default -> "Weekend";
        };
        
        System.out.println(result);
    }
}

Explanation:

  • The new syntax allows the use of -> for specifying the case blocks.
  • The result is returned directly from the switch expression and can be assigned to a variable.

Output:

Wednesday

Best Practices for Using switch

  1. Use switch for discrete values: The switch statement is most useful when comparing a variable against discrete values, such as integers, characters, or strings.
  2. Avoid complex conditions: switch is not suitable for conditions that involve ranges or complex logic (for that, use if-else).
  3. Leverage the default case: Always include a default case to handle unexpected values, especially when dealing with user input or unknown values.
  4. Use switch expression (Java 12+): If you’re using Java 12 or later, consider using the new switch expression for cleaner and more readable code.