Switch-case syntax

The switch statement in Java is a control flow statement that is used to evaluate an expression and execute different code blocks based on the value of the expression.

The basic syntax of the switch statement is:

switch(expression) {
   case value1 :
      // code block
      break;
   case value2 :
      // code block
      break;
   case value3 :
      // code block
      break;
   // you can have any number of case statements
   default :
      // code block
}

Here, the expression is evaluated and the code block corresponding to the value of the expression is executed. If there is no match, then the default code block is executed.

The switch statement is often used as an alternative to if-else statements when there are many possible conditions to evaluate. The switch statement can be more efficient than if-else statements when there are a large number of conditions.

It’s worth noting that in Java, the expression in a switch statement must be of an integral type (byte, short, int, or char), an enumeration, or a string. The values used in the case statements must also be of the same type.