How to use the Switch Expression in Java 14

dimitrilc 3 Tallied Votes 121 Views Share

Introduction

Java 14 was released with a new type of expression called Switch Expression. Its syntax is similar to that of the Switch Statement, with a few differences.

In this tutorial, we will walk through concepts related to the Switch Expression and learn how to use it.

Goals

At the end of this tutorial, you would have learned:

  1. The following concepts of Switch Expression: Arrow Label and Yielding.
  2. How to use the Switch Expression.

Prerequisite Knowledge

  • Basic Java.

Tools Required

  • An IDE with support for JDK 14+

Project Setup

Before writing any code, we need to set up our project first. Below are the steps to set up our project:

  1. Create a new vanilla Java project.
  2. Create the package com.example.switcher. This is where our main method lives.
  3. Create a public Java class Entry.java.
  4. Add the main method to Entry.java.
  5. Add an enum Season with 4 constants representing 4 seasons SPRING, SUMMER, FALL, WINTER. This enum has the package-private access modifier.

Your code should now look like this.

    package com.example.switcher;

    public class Entry {

       public static void main(String[] args){

       }

    }

    enum Season { SPRING, SUMMER, FALL, WINTER }

The Arrow Label

The first concept that we will look at is the arrow label. Instead of the colon label : used in switch statements, an arrow -> indicates that the current switch block is a Switch Expression.

Copy the 2 methods below into the Entry class to see how it is used.

    private static void arrowSwitch(Season season){
       switch(season){
           case SPRING -> System.out.println("It is Spring.");
           case SUMMER -> System.out.println("It is Summer.");
           case FALL -> System.out.println("It is Fall.");
           case WINTER -> System.out.println("It is Winter");
       }
    }

    private static Season arrowSwitch2(Season season){
       return switch (season){
           case SPRING -> Season.SPRING;
           case SUMMER -> Season.SUMMER;
           case FALL -> Season.FALL;
           case WINTER -> Season.WINTER;
       };
    }

Inside main(), they are called like this:

    public static void main(String[] args){
       arrowSwitch(Season.SPRING);
       System.out.println(arrowSwitch2(Season.FALL));
    }

And the output is:

It is Spring.
FALL

Here are the explanations for the code above:

  1. The first method arrowSwitch() is meant as a simple comparison to the switch statement. If you have not noticed, there is no break keyword and the case statements do not fall through. In a switch expression, there is only one matching case and the expression exits when a matching case is found, so we do not have to worry about the fall-through behavior of the old switch statement.
  2. The second method arrowSwitch2() is meant to show another behavior of switch expressions. Because they are expressions, they evaluate to a value, so it is possible to return a switch expression directly.

The yield Statement

Even though the arrow label -> definitely makes a switch block a switch expression, that does not mean the colon label : cannot be used inside a switch expression.

A colon label can be used inside a Switch Expression, but this syntax reintroduces the fall-through behavior and developers must use the yield keyword to cause the expression to evaluate to a value, therefore stop falling through.

Add the method below to the Entry class.

    private static Season colonSwitchExpression(Season season){
       return switch (season){
           case SPRING:
               System.out.println("It is Spring.");
               //yield Season.SPRING;
           case SUMMER:
               System.out.println("It is Summer.");
               //yield Season.SUMMER;
           case FALL:
               System.out.println("It is Fall.");
               //yield Season.FALL;
           case WINTER:
               System.out.println("It is Winter");
               yield Season.WINTER;
       };
    }

And call it in main() like the snippet below.

    public static void main(String[] args){
       //arrowSwitch(Season.SPRING);
       //System.out.println(arrowSwitch2(Season.FALL));
       colonSwitchExpression(Season.SPRING);
    }

And the program will print all the sysout calls because after matching with SPRING, the switch expression keeps falling through until it finds a yield statement.

It is Spring.
It is Summer.
It is Fall.
It is Winter

If we uncomment the 3 yield statements in the code above, then the switch expression will stop falling through.

It is recommended to always use the arrow label -> with switch expressions to avoid accidental fall through.

Solution Code

    package com.example.switcher;

    public class Entry {

       public static void main(String[] args){
           //arrowSwitch(Season.SPRING);
           //System.out.println(arrowSwitch2(Season.FALL));
           colonSwitchExpression(Season.SPRING);
       }

       private static void arrowSwitch(Season season){
           switch(season){
               case SPRING -> System.out.println("It is Spring.");
               case SUMMER -> System.out.println("It is Summer.");
               case FALL -> System.out.println("It is Fall.");
               case WINTER -> System.out.println("It is Winter");
           }
       }

       private static Season arrowSwitch2(Season season){
           return switch (season){
               case SPRING -> Season.SPRING;
               case SUMMER -> Season.SUMMER;
               case FALL -> Season.FALL;
               case WINTER -> Season.WINTER;
           };
       }

       private static Season colonSwitchExpression(Season season){
           return switch (season){
               case SPRING:
                   System.out.println("It is Spring.");
                   yield Season.SPRING;
               case SUMMER:
                   System.out.println("It is Summer.");
                   yield Season.SUMMER;
               case FALL:
                   System.out.println("It is Fall.");
                   yield Season.FALL;
               case WINTER:
                   System.out.println("It is Winter");
                   yield Season.WINTER;
           };
       }

    }

    enum Season { SPRING, SUMMER, FALL, WINTER }

Summary

In this tutorial, we have learned how to use the Switch Expression that was released alongside JDK 14.

The full project code can be found at https://github.com/dmitrilc/DaniWebJavaSwitchExpression