Java:  The Evolution Switch (JEP 361)

Java: The Evolution Switch (JEP 361)

Clean and Concise Switch Expressions

Subscribe to my newsletter and never miss my upcoming articles

Java switch expressions have been evolving with JDK release, while other JVM-based languages have been giving the compact and clean syntax, Java has waited as always and finally made the switch look a lot better. Let's explore the Java switch expressions for now. Look at the sample code below where switch expression will help to choose the breakfast based on the DAY of the week. Obviously, it is easy but has few pain points which make it error-prone and verbose.

enum DAYS {
        SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
    }

Now, let us write switch in the old way.

 switch (DAY) {
            case SATURDAY:
            case SUNDAY:
                System.out.println("It's Weekend Yay !");
                System.out.println("Toast");
                break;
            case MONDAY:
                System.out.println("Poha");
                break;
            case TUESDAY:
                System.out.println("Oats");
                break;
            case WEDNESDAY:
                System.out.println("Smoothie");
                break;
            case THURSDAY:
                System.out.println("Dosa");
                break;
            case FRIDAY:
                System.out.println("Bagel");
                break;
        }
  • The above code will work but what if you forget to write break, Yes, it will break all of your code and all of the options which you have written after your switch value will be executed.
  • It is quite verbose, a lot of code for little work.

Now, we will see how JEP 361 for Java 14 makes it easier and simple. The same switch can be written as below code

String breakFast = switch (DAY) {
            case SATURDAY, SUNDAY -> {
                System.out.println("It's Weekend Yay !");
                yield "Toast";
            }
            case MONDAY -> "Poha";
            case TUESDAY -> "Oats";
            case WEDNESDAY -> "Smoothie";
            case THURSDAY -> "Dosa";
            case FRIDAY -> "Bagel";
        };
  • Do note that now, it is an expression not only a statement, It also returns the value.
  • One more interesting thing to note is that return from the block is using yield rather return . This is done to avoid confusion whether it is the method return or the return from the switch block
  • We don't require a break to terminate the execution of flow. It will only execute the code it is meant to execute by its arrow function
 
Share this