Core Java

Java 14 Switch Expressions

In this article, we will see one of the new features of Java 14 which are the Switch Expressions. Switch Expressions is an evolution of the Switch statement in Java, that was used as a decision code block. 

1. Introduction

Below, are the subjects that we’ll look in the article:

  • Traditional Switch case
  • Switch Expressions in Java 14
  • Using Lambdas

We start taking a look at the traditional way to make a switch case, and later we’ll do a refactor to use the switch expressions with Java 14 and also take the lambda expression to enhance our code.

2. Technologies Used

For this example, the technologies used are:

  • JDK 14 – download here
  • IntelliJ IDEA 2020.2 – download here

You can use any IDE or text editor of your knowledge, but make sure that supports JDK 14.

3. Hands-on

Now, let’s begin to work with this new feature, coding a few lines and refactoring later to get a good understanding.

3.1 Traditional Switch Case

First, we will create an enum that contains the days of week.

Enum
package example.com.srg;

public class SwitchExpressionsExample {
    enum WEEK_DAYS { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY};

After that, let’s create a method with a basic switch case to go through this enum.

Swtich Case Traditional
private static String switchTraditional(WEEK_DAYS dayOfWeek) {
        String result = null;

        switch (dayOfWeek){
            case  MONDAY:
            case  TUESDAY:
            case  WEDNESDAY:
            case  THURSDAY:
            case  FRIDAY:
                result = "Work day";
                break;
            case SATURDAY:
            case SUNDAY:
                result = "Rest day";
                break;
            default: result ="Invalid";
        }
        return result;
    }

As we can see, it’s a basic switch case block that will break when matching the correct matching and have a default value if the value is invalid. 

Let’s print the result creating a void main method to execute or switch method:

Main method
public static void main(String[] args) {
        System.out.println(switchTraditional(WEEK_DAYS.MONDAY));
    }

The result is in the following:

/Library/Java/JavaVirtualMachines/jdk-14.0.1.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar=50526:/Applications/IntelliJ IDEA CE.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Users/slauriano/dev/java/out/production/java example.com.srg.SwitchExpressionsExample
Work day

Process finished with exit code 0

As expected, the result is printed as “Work day”.

3.2 Switch expressions in Java 14

Now, we’ll do a refactor in our code, creating a new method using the Java 14 Switch Expressions.

Switch Expression in Java 14
private static String switchJava14(WEEK_DAYS dayOfWeek) {
        return switch (dayOfWeek) {
            case MONDAY:
            case TUESDAY:
            case WEDNESDAY:
            case THURSDAY:
            case FRIDAY:
                yield "Work day";
            case SATURDAY:
            case SUNDAY:
                yield "Rest day";
        };
    }

We can see a new word called “yield” that was introduced in Java 12 and 13, but now can be fully used in Java 14. So, switch now is not just a block of code, but is an expression with a return. The yield word will make the return that could be also a logic to be executed inside.

Refactoring the void main method:

Main method
public static void main(String[] args) {
        System.out.println(switchJava14(WEEK_DAYS.MONDAY));
    }

And the result again “Work day”:

 /Library/Java/JavaVirtualMachines/jdk-14.0.1.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar=50630:/Applications/IntelliJ IDEA CE.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Users/slauriano/dev/java/out/production/java example.com.srg.SwitchExpressionsExample
Work day

Process finished with exit code 0

3.3 Using Lambdas

To improve our code, we can do another refactoring using lambda expressions in the switch expression:

Switch Expression with LambdaSwitchingExpressionsExample.java
private static String switchEnhanced(WEEK_DAYS dayOfWeek) {
        return switch (dayOfWeek) {
            case MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY -> "Work day";
            case SATURDAY, SUNDAY -> "Rest day";
        };
    }

As we notice, the yield word is not necessary anymore when using lambda arrow expression.

Changing the void main method:

Main method
public static void main(String[] args) {
        System.out.println(switchEnhanced(WEEK_DAYS.MONDAY));
    }

And the result as expected:

 /Library/Java/JavaVirtualMachines/jdk-14.0.1.jdk/Contents/Home/bin/java -javaagent:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar=50630:/Applications/IntelliJ IDEA CE.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Users/slauriano/dev/java/out/production/java example.com.srg.SwitchExpressionsExample
Work day

Process finished with exit code 0

4. Summary

I this article, we could see how the switch case changed in Java 14, by refactoring the traditional way to do a switch case and also using a lambda expression with it. For more details about Switch Expressions, take a look on the JEP on this link.

5. Download the Source Code

Download
You can download the full source code of this example here: Java 14 Switch Expressions

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Sergio Lauriano Junior

Sergio is graduated in Software Development in the University City of São Paulo (UNICID). During his career, he get involved in a large number of projects such as telecommunications, billing, data processing, health and financial services. Currently, he works in financial area using mainly Java and IBM technologies.
Subscribe
Notify of
guest

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

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Alvaro
Alvaro
2 years ago

Nice!, great job!

Back to top button