Java 12's Switch Expressions in 5 minutes

Java 12's Switch Expressions in 5 minutes

The version 12 of Java comes with a new preview feature (amongst others): Switch Expressions. Let’s see how this feature can simplify some of our daily tasks.

Java 12 Switch Expressions
Table of Contents

Java 12’s Simplified Switch Block

Classic switch block in Java

Before the release of this new preview feature, the only way to write a switch block in Java implies the usage of case: (with a colon):

int numDays;
switch (month) {
    case 1: case 3: case 5:
    case 7: case 8: case 10:
    case 12:
        numDays = 31;
        break;
    case 4: case 6:
    case 9: case 11:
        numDays = 30;
        break;
    case 2:
        numDays = isLeap(year) ? 29 : 28;
        break;
    default:
        throw new IllegalArgumentException("Invalid month number");
}

When you use the classic case:, the concept of fall-through applies. All subsequent case blocks will also be executed until it reaches a break statement (or you use return within a method, or you throw an exception). This is still helpful in some scenarios but normally is just used to group multiple cases when they all share the same code (as shown above for a group of months).

The fall-through concept is error-prone because you may easily forget a break statement and introduce a bug. Also, it makes your code less readable.

The new arrow syntax in switch blocks

The Simplified Switch Block feature introduces the arrow syntax as an option to use instead of the colon: case ->. If you use this new syntax, only the expression or statement to the right of the arrow is executed.

int numDays;
switch (month) {
    case 1 -> numDays = 31; // don't need the break statement
    case 4 -> numDays = 30; // not executed if month = 1
    // ...
}

This removes the necessity for break statements. However, the arrow syntax by itself does not help with grouping switch cases. That requirement has been taken into account and now it’s possible to do that in a shorter, more convenient way, just by using commas:

int numDays;
switch (month) {
    case 1, 3, 5, 7, 8, 10, 12 -> numDays = 31;
    case 4, 6, 9, 11 -> numDays = 30;
    case 2 -> numDays = isLeap(year) ? 29 : 28;
    default -> throw new IllegalArgumentException("Invalid month number");
}

The code is now much more concise and readable.

Get the book Practical Software Architecture

Java 12’s Switch Expressions

In the example code we’ve been using, you can see that the goal is to assign a value to a variable (numDays). This is a common use of a switch block in Java.

With Switch Expressions, you can now avoid that repetitive code and use switch as an expression to assign a value to the variable. This feature is available in Java 12 only as a preview, so you have to enable it explicitly (see next section).

int numDays = switch (month) {
    case 1, 3, 5, 7, 8, 10, 12 -> 31;
    case 4, 6, 9, 11 -> 30;
    case 2 -> isLeap(year) ? 29 : 28;
    default -> throw new IllegalArgumentException("Invalid month number");
};

The difference is that you replace the assignments by just a value. This approach is similar to the ternary operator we’ve been using in this example since the beginning:

numDays = isLeap(year) ? 29 : 28;

To avoid this:

if (isLeap(year))
  numDays = 29;
else
  numDays = 28;

Therefore, Switch Expressions allow you to extend these assignments to cases when there are more than two options, using them as you would use the ternary operator in assignments.

Running the example code

Getting JDK 12

First, you need to get the JDK 12. To download it, you can visit the OpenJDK site: https://jdk.java.net/12/.

Getting the source code

The source code used in this example is available on GitHub: JDK Switch Expressions Example. You can clone the repository using git or download a zip file with its contents using the web interface.

Run Java 12 Preview Features with Maven

The pom.xml file in the repository uses the maven-compiler-plugin configuration to specify the --enable-preview argument, which is needed to activate this feature in JDK 12.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.0</version>
            <configuration>
                <release>12</release>
                <compilerArgs>--enable-preview</compilerArgs>
            </configuration>
        </plugin>
        ...
    </plugins>
</build>

Then, you only need to ensure that Maven is using JDK 12 to build. To do that, the best option is changing your JAVA_HOME to point to the new JDK distribution. The following command will build the code using Java 12’s compiler and generate a JAR file:

$ mvn clean package

Now you have to make sure that the java executable is also the JDK 12 version. As usual, you just need to change your PATH environment variable (Windows) or switch the active Java VM (mac and linux). To verify it, you can run:

$ java -version 
openjdk version "12.0.2" 2019-07-16
OpenJDK Runtime Environment (build 12.0.2+10)
OpenJDK 64-Bit Server VM (build 12.0.2+10, mixed mode, sharing)

Finally, you can run the JAR file since the repository includes configuration to make it executable. It executes only one of the code examples but you can alter the MANIFEST.MF contents so it runs the ClassicSwitch class.

Other recent Java features

Check out these other articles about other -relatively- recent Java features:

If you want to support this site, you can also have a look at my book: Learn Microservices with Spring Boot. It follows a practical approach like this article.

Moisés Macero's Picture

About Moisés Macero

Software Developer, Architect, and Author.
Are you interested in my workshops?

Málaga, Spain https://thepracticaldeveloper.com

Comments