Skip to content

Switch Expressions in Java – A quick introduction

In this post, we will quickly go through Switch Expressions which was introduced as a preview feature in JDK 12 and with yield keyword in JDK 13.

The primary motive of Switch Expressions is to resolve several irregularities of the existing switch statement — which have long been an irritation to users — become impediments. These include the default control flow behavior between switch labels (fall through), the default scoping in switch blocks (the whole block is treated as one scope), and the fact that switch works only as a statement, even though it is often more natural to express multi-way conditionals as expressions.

A new form of switch label, “case L ->“, to signify that only the code to the right of the label is to be executed if the label is matched.

static void getWeekday(int day) {
    switch (day) {
        case 1  -> System.out.println("Sunday");
        case 2  -> System.out.println("Monday");
        case 3  -> System.out.println("Tuesday");
        case 4  -> System.out.println("Wednesday");
        case 5  -> System.out.println("Thursday");
        case 6  -> System.out.println("Friday");
        case 7  -> System.out.println("Saturday");
        default -> System.out.println("Invalid day");
    }
}
getWeekDay(2); //Monday
getWeekDay(99); //Invalid day

Extend the switch statement so it can be used as an expression.

The above code can be reduced by having a one println outside and switch expression inside.

static void getWeekday(int day) {
    System.out.println(
        switch (day) {
        case 1  -> "Sunday"
        case 2  -> "Monday"
        case 3  -> "Tuesday"
        case 4  -> "Wednesday"
        case 5  -> "Thursday"
        case 6  -> "Friday"
        case 7  -> "Saturday"
        default -> "Invalid day"
        }
    );
}

A new yield statement to yield a value, which becomes the value of the enclosing switch expression

If you want to have a full block of code on the right side of ‘case L’ and return a value from the block, you can use yield statement. This becomes the returning value of the enclosed switch expression.

String dayString = switch (day) {
        case 1  -> "Sunday";
        case 7  -> "Saturday";
        default -> {
          if(day > 1 && day < 7)
           yield "Not weekend!";
        }
    );

yield can also be used in traditional switch statement.

String dayString = switch (day) {
    case 1:
      yield "Sunday";
    case 7:
      yield "Saturday";
    default:
      yield "Not weekend!";
    );

You can’t use yield() and -> in the same block.

See also  Print characters from a to z using loop in Java

The cases of a switch expression must be exhaustive; for all possible values there must be a matching switch label.

The cases of a switch expressions must exhaust all possible values there must be for matching switch label. It’s not the same case (pun not intended) with the traditional switch statement though. The compiler checks that for all possible enum values there is a matching switch label, which helps reducing scope for bugs.

String result = switch (day) {
    case SUNDAY, SATURDAY -> "S";
    case TUESDAY, THURSDAY -> "T";
}

// Compilation error:
//     "the switch expression does not cover all possible input values"

You have to cover all the cases. If you cover all scenarios, you don’t need a default case.

String result = switch (day) {
    case SUNDAY, SATURDAY -> "S";
    case TUESDAY, THURSDAY -> "T";
    case WEDNESDAY -> "W";
    case FRIDAY -> "F";
    case MONDAY -> "M";
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.