Index


Java switch Statement

Instead of writing many if..else statements, you can use the switch statement.

The switch statement selects one of many code blocks to be executed:

Syntax:

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

oss

The default value catch all the not specified cases


Example + Compact version


Java yield

  • The keyword “yield” in Java is used in switch expressions to provide a returned value
  • The “yield” keyword allows you to exit a switch expression by returning a value, which becomes the value of the switch expression.

Example:

String number = switch (number) {
    case 1:
        yield "one";
    case 2:
        yield "two";
    default:
        yield "Zero";
}