Sobes.tech
Junior — Middle

Can you explain how the switch statement works and how it differs from other conditional constructs?

sobes.tech AI

Answer from AI

The switch operator is used to select one of several blocks of code to execute based on the value of an expression. It compares the expression's value with a set of constant values (cases) and executes the corresponding block of code.

Differences from other conditional operators (e.g., if-else):

  • switch is usually more convenient and readable when you need to check one expression against multiple specific values.
  • In switch, comparison is only with constants, whereas in if, any conditions can be used.
  • In some languages, switch can work faster because the compiler optimizes the jumps.

Example in Java:

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;
    default:
        System.out.println("Other day");
}

Here, if day equals 3, "Wednesday" will be printed. The break keyword prevents the execution of subsequent cases.