Module: Control Flow in Java

switch-case

Java Core: Control Flow - switch-case Statement

The switch-case statement is a multi-way decision-making statement in Java. It provides a more efficient and readable alternative to a series of if-else if-else statements when you need to compare a single variable against multiple possible values.

Syntax:

switch (expression) {
  case value1:
    // Code to execute if expression == value1
    break;
  case value2:
    // Code to execute if expression == value2
    break;
  ...
  case valueN:
    // Code to execute if expression == valueN
    break;
  default:
    // Code to execute if expression doesn't match any case
}

Explanation:

  • switch (expression): The expression is evaluated. This expression must evaluate to an integer type (byte, short, char, int) or a String (Java 7 and later) or an enum type (Java 5 and later).
  • case value1:: Each case label represents a specific value to compare against the expression.
  • // Code to execute...: If the expression matches the value1, the code block associated with that case is executed.
  • break;: The break statement is crucial. It terminates the switch statement after a matching case is executed. Without break, execution will "fall through" to the next case, even if it doesn't match.
  • default:: The default case is optional. It provides a block of code to execute if the expression doesn't match any of the case values. It's good practice to include a default case to handle unexpected values.

Example 1: Using switch-case with int

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;
  case 6:
  case 7: // Combining cases
    System.out.println("Weekend");
    break;
  default:
    System.out.println("Invalid day");
}

Output:

Wednesday

Example 2: Using switch-case with String (Java 7+)

String fruit = "apple";

switch (fruit) {
  case "apple":
    System.out.println("It's an apple!");
    break;
  case "banana":
    System.out.println("It's a banana!");
    break;
  case "orange":
    System.out.println("It's an orange!");
    break;
  default:
    System.out.println("Unknown fruit");
}

Output:

It's an apple!

Example 3: Using switch-case with enum (Java 5+)

enum Color {
  RED, GREEN, BLUE
}

public class EnumSwitch {
  public static void main(String[] args) {
    Color color = Color.GREEN;

    switch (color) {
      case RED:
        System.out.println("The color is red.");
        break;
      case GREEN:
        System.out.println("The color is green.");
        break;
      case BLUE:
        System.out.println("The color is blue.");
        break;
      default:
        System.out.println("Unknown color.");
    }
  }
}

Output:

The color is green.

Key Points:

  • break is essential: Always include break statements to prevent fall-through.
  • default is optional but recommended: Handles unexpected values gracefully.
  • Data Types: The expression in the switch statement must be of a limited set of types: byte, short, char, int, String (Java 7+), or an enum type (Java 5+).
  • Case Values: case values must be constant expressions. You cannot use variables or expressions that are evaluated at runtime.
  • Combining Cases: You can combine multiple case labels if they should execute the same code. (See Example 1, case 6: and case 7:)
  • Readability: switch-case statements often improve code readability compared to long if-else if-else chains, especially when dealing with multiple possible values.

When to use switch-case:

  • When you need to compare a single variable against a fixed set of possible values.
  • When readability is important.
  • When performance is critical (in some cases, switch-case can be more efficient than a long if-else if-else chain).

When not to use switch-case:

  • When you need to compare against ranges of values (use if-else if-else instead).
  • When the conditions are complex and involve multiple variables.
  • When the number of cases is very large and constantly changing (consider using a Map or other data structure).