Categories
Java

Switch expressions

This feature was introduced in Java 12 and allows you to use the switch statement in a more powerful and expressive way, by allowing to return a value or to assign a value to a variable directly from the switch statement.

With switch expressions, you can use the switch statement in combination with an arrow operator -> and the variable declaration or assignment, and the compiler will automatically extract the value of the matched case and return it or assign it to the variable.

Here’s an example of how using switch expressions can be more useful and efficient than the previous traditional way of using if-else statements:

enum Size {
    SMALL, MEDIUM, LARGE, EXTRA_LARGE;
}

int getDiscount(Size size) {
    return switch (size) {
        case SMALL -> 5;
        case MEDIUM -> 10;
        case LARGE -> 15;
        case EXTRA_LARGE -> 20;
    };
}

In this example, we have an enum Size which has 4 possible values, and we want to return a discount percentage based on the value of the size enum.

Using switch expressions, we can use the switch statement to match the values of the size enum, and the corresponding case will be selected and the value following the arrow operator will be returned. This way the code is more concise, readable, and efficient.

Without switch expressions, we would have to use the traditional if-else statements, like this:

int getDiscount(Size size) {
    if (size == Size.SMALL) {
        return 5;
    } else if (size == Size.MEDIUM) {
        return 10;
    } else if (size == Size.LARGE) {
        return 15;
    } else if (size == Size.EXTRA_LARGE) {
        return 20;
    } else {
        throw new IllegalArgumentException("Invalid size: " + size);
    }
}

As you can see, in the above example, the code is more verbose, less readable and not as efficient.

Leave a Reply

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