Switch Expressions in Java (JEP 361)

With Java 14 we will get a new feature that simplifies the switch statement. It will provide a new and clearer way to write switch statements and in addition allows us to use switch as an expression yielding a value.

New Syntax

Forget about break! No fall through anymore – simple and concise.

switch (day) {
    case MONDAY             -> System.out.println("Fully motivated!");
    case TUESDAY, WEDNESDAY -> System.ouFt.println("Get this done!");
    case THURSDAY, FRIDAY   -> System.out.println("Almost done!");
    case SATURDAY, SUNDAY   -> System.out.println("Party time!");
}

Today you would write something like below. Don’t miss the breaks!

switch (day) {
   case MONDAY:
       System.out.println("Fully motivated!");
       break;
   case TUESDAY:
   case WEDNESDAY: 
        System.ouFt.println("Let's get this done!");
        break;
   case THURSDAY:
   case FRIDAY:   
       System.out.println("Almost done!");
       break;
   case SATURDAY:
   case SUNDAY:
       System.out.println("Party time!");
}

Switch Expressions

This is really cool. Now we can asisgn the result of a switch expression to a variable.

String workingDay = switch(day) {
    case 1,2,3,4,5 -> "yes";
    case 6,7 -> "no";
    default -> "don't know";
};

This is easy to read and allows us to simplify our code. Maybe until now you used nested conditional operators (!!) or you introduced a little helper method with return statements.

If you need an actual block to calculate the result of the expression, there is a new keyword you can use for that purpose: yield

String workingDay = switch(day) {
    case 1,2,3,4,5 -> "yes";
    case 6,7 -> "no";
    default -> {
       String defaultAnswer = calculateDefaultAnswer();
       yield defaultAnswer;
    }
};

You can also use the legacy switch syntax and form expressions using the yield keyword.

int result = switch (s) {
    case "Foo": 
        yield 1;
    case "Bar":
        yield 2;
    default:
        System.out.println("Neither Foo nor Bar, hmmm...");
        yield 0;
};

It’s an expression baby

Image result for coding meme

Yes, you can drive your co worker crazy by building complex and inlined switch expressions. It works – I tried it.

public static boolean isWorkingDay(String day) {        
    if ("yes".equals(switch (day) { case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" -> "yes"; case "Saturday", "Sunday" -> "no"; default -> "dont' know";})) {
        return true;
    } else {
        return false;
    }
}

Try it out today

You can download early access builds from https://jdk.java.net/14/ (just unzip it somewhere you find it again). With Java 14 this is not a preview feature anymore, so you can just start to use the new switch expressions.

Personal opinion

In short: I really like it. I think it makes a lot of sense. Having the privilege to also teach classes in programming I can say that the intention of the programmer when using the switch statement was always a different one – always.

In addition using switch as an expression provides new ways also for a seasoned programmer to simplify their code. Have you ever seen those nested tenary conditional operators?

One downside I see is developers thinking that it is cool to inline switch expressions and combine them to more complex expressions that no one will ever touch again.

Image result for i can do it meme

1 comment

  1. Not sure why it took so long to implement this syntax for switch. Previously I never used switch because it was far too verbose, and this only left the if statement. I always thought that it would be relatively easy to implement an additional statement (or switch option) that functioned the same but removed the need for break. Sure, nothing would be simple to implement in something as big as Java, but relative to everything else. I’m sure that the Java developers want people to use Java, so I simply cannot understand why this took so long. This really is a big deal. Great to see this enhancement to Java and may more follow.

Leave a comment

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.