Java

JDK 12 – JEP 325 Switch Expressions

JDK 12 went GA on March 19, 2019, keeping its word on shorter release cycles and frequent releases. The features part of the release can be found here. One of the interesting features for the developers is the “JEP 325 Switch Expressions” which is available as a preview feature.

A preview feature as defined here is:

A preview language or VM feature is a new feature of the Java SE Platform that is fully specified, fully implemented, and yet impermanent. It is available in a JDK feature release to provoke developer feedback based on real world use; this may lead to it becoming permanent in a future Java SE Platform.

In this article, I will show you how switch has evolved from being a statement to become an expression. A statement is something that executes but doesn’t evaluate to some value whereas expression is something that on execution evaluates to a value:

//Statement
System.out.println("This is a statement");

//Expression
6 + 5;

Switch as expressions

The syntax for the switch as expressions has changed:

Object switchResult = switch ( variable ) {
    case choice1 -> result1;
    case choice2 -> result2;
    default -> resultDefault;
}

In addition to the above use of a switch, it can be used as a statement as well:

switch( variable ) {
    case choice1: 
      doSomeThing(); 
      break;
    case choice2:
      doOtherThing();
      break;
    default:
      doDefaultThing();
}

I am not going into the motivation for introducing the switch expressions. You can read about it here. The remaining part of the article will show how the switch can be used as an expression. The below code snippet shows the use of switch as an expression, observe that switch now is yielding a value which in this case is boolean:

public static boolean isHealthy(String food){
    return switch (food){
        case "Fruit"  -> true;
        case "Vegetable" -> true;
        case "Pizza" -> false;
        case "Burger" -> false;
        case "Pulses" -> true;
        case "Soft Drink" -> false;
        default -> false;
    };
}

System.out.printf("Fruit is %s\n" , isHealthy("Fruit"));

From the code snippet above, we can see that the expression used in the switch can now be a string as well. This is applicable for both in the statement and the expression.

If the possibility of the values of the expression being evaluated is not a fixed set, then we need to provide the default block. If we are using an enum as switch expression, then we don’t need to provide default case because the possible outcomes in the enum are limited to the enum values. This is shown in the example below:

enum Food {
    Fruit, Vegetable, Pizza, Burger, Pulses, Soft_Drink
}

public static boolean isHealthEnumVersion(Food food){
    return switch (food){
        case Fruit -> true;
        case Vegetable -> true;
        case Pizza -> false;
        case Burger -> false;
        case Pulses -> true;
        case Soft_Drink -> false;
    };
}

System.out.printf("Pizze is %s\n", isHealthEnumVersion(Food.Pizza));

Another example where we put the result of method evaluation as an expression in the switch:

public static int evaluateLunch(Food food){
    return switch (isHealthEnumVersion(food).toString()){
        case "true" -> 10;
        case "false" -> 5;
        default -> 0;
    };
}

System.out.printf("Your food received %d points\n",
        evaluateLunch(Food.Burger));

Block of code as case evaluation

In the previous examples, we saw the case was mapped against single line expressions. How do we deal with when we need a block of code to be evaluated for the case?

public static PreparedFood prepareFood(Food food){
    return switch (food){
        case Pizza -> {
            System.out.println("doing pizza related operations");
            break new PreparedFood(food);
        }
        case Burger -> {
            System.out.println("Doing burger related operations ");
            break new PreparedFood(food);
        }
        default -> {
            System.out.printf("Doing %s related operations\n",
               food.toString());
            break new PreparedFood(food);
        }
    };

}

You can notice that the break has been enhanced to accept a parameter, which becomes the result of the evaluation of the code block against the case.

Switch as an expression using the old syntax

We can stick to the old syntax of switch i.e without the -> symbol, as shown below:

public static int evaluateLunchOldWay(Food food){
    return switch (isHealthEnumVersion(food).toString()){
        case "true": break 10;
        case "false":  break 5;
        default: break 0;
    };
}

The complete code for this article can be found here.

Advertisements

Categories: Java, Java 12

Tagged as:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

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