Estimate project
← All posts

Java 21: turning on the power of switch

The article traces how Java's switch statement has evolved and shows how to use the new Java 21 features for fine-grained pattern matching on nested records

10 min read
javajava21uncoverjavapattern matchingswitch

The revamped switch expression (no longer a statement) has been available since Java 14. Back then, though, it could only match on constant values. Java 21 brings pattern matching for switch, which lifts the switch to an entirely new level.

In this article, I’ll guide you through the new features and show how powerful the new switch becomes when paired with record types and sealed type hierarchies. Let’s dive in!

The fundamentals

We’ll begin with a short reminder of what the switch expression can do. Take a look at the first example, and then we’ll go over the key parts:

enum Direction {
    NORTH, SOUTH, EAST, WEST;

    int bearing() {
        return switch (this) {                          // (1)
            case NORTH -> 0;                            // (2), (3)
            case SOUTH -> 180;
            case EAST -> 90;
            case WEST -> {
                System.out.println("Go west!");
                yield 270;                              // (4)
            }
        };
    }
}

Expression with arrow labels

If you caught the small difference in wording, i.e., “statement” vs. “expression” – it’s intentional. Prior to Java 14, switch was only a statement, i.e. a control structure, whereas the new switch is an expression: it produces a value, so it can be assigned to a variable or returned directly, as in (1).

The new switch comes with fresh syntax – so-called “arrow labels” (2), which may be followed by either a single expression or a block. A single expression to the right of the arrow (3) is the value to be returned (keep in mind that it’s an expression now). When the right-hand side of the arrow needs a block containing several statements, you must use the new yield keyword (4).

No fall-through

Have you spotted that there are no break statements? With arrow labels, they are no longer necessary. Fall-through doesn’t happen by default, so evaluation stops at the first case that matches – which in turn means that ordering matters, i.e., more specific cases must come first.

Exhaustiveness check

Try commenting out case NORTH -> 0; – what’s the result? The compiler should begin to complain:

java: the switch expression does not cover all possible input values

This comes from the exhaustiveness check, i.e., the compiler verifying that the switch expression handles every possible value – which spares you surprises at runtime. Moreover, there’s no need for a default branch “just in case”: once the code compiles, you can be sure every case is handled.

You can still add a default case to get around this compilation error, but thanks to the compile-time check, doing so has to be a conscious choice.

What’s great about the exhaustiveness check is that it isn’t limited to enums – we’ll come back to this later.

Pattern matching

Java 21 brings pattern matching – a powerful feature found in many programming languages (Scala, Haskell or Rust, among others) that allows you to examine an object’s structure rather than just its value. On top of that, it can be used to pull data out of nested object structures while at the same time checking whether particular conditions hold.

Extract and check the data

Take a look at this example:

public record Point(int x, int y) {
}

class Cartesian {

    static void printQuadrant(Point p) {
        switch (p) {
            case Point(var x, var y) when x > 0 && y > 0 -> 
                System.out.println("first");
            default -> 
                System.out.println("other");
        }
    }
}

Surely you’ve noticed that plenty of new things are going on in this line:

case Point(var x, var y) when x > 0 && y > 0 ->

Here, we are:

  • verifying whether the matched value is of type Point,
  • pulling out the values of the x and y fields so they can be used without going through a Point instance (note that the compiler can infer the types of x and y, so you may write var rather than the actual type),
  • verifying with the new when keyword whether the point’s coordinates meet a given condition.

To get a comparable result in an older Java version, you would write something along these lines:

if (p instanceof Point) {
    Point point = (Point) p;

    if (p.x() > 0 && p.y() > 0) {
        System.out.println("first");
    } else {
        System.out.println("other");
    }
}

The pattern matching syntax is far more concise, wouldn’t you agree?

Bear in mind that pattern matching works not only with the switch expression but also with the instanceof keyword. So in Java 21 you can still write this example using instanceof, only much more briefly:

if (p instanceof Point(var x, var y) && x > 0 && y > 0) {
    // ...
}

Here there’s no when keyword, but apart from that, the pattern matching, extraction, and condition check look much like in the switch version.

Null labels

What if the Point p handed to printQuadrant is null? Correct – you get a NullPointerException. That still holds in Java 21, but you now have a handy way of dealing with the null case explicitly via case null ->, which helps you steer clear of the NPE.

Keep in mind that in this code:

String test = null;

switch (test) {
    case String s -> System.out.println("String");
    case null -> System.out.println("null");
}

the null label is still the one that matches, even though s has the type String.

Unleash the power of switch and pattern matching

Up to this point, we’ve looked at a few simple examples of how the switch expression and pattern matching behave. Their real strength, however, shows only when you begin working with more complex data types.

Errors as values

For the following example, let’s take a trip into the world of functional programming, where everything is a value – errors included. Keeping that in mind, rather than signalling errors with exceptions, let’s represent them as values.

An advantage of this approach is that a single mechanism (the return value) expresses both the successful and the failing behavior of your program, rather than relying on separate mechanisms for each scenario (return values or exceptions).

As an operation can end either with an error or with a success (in which case it returns a value), let’s model the outcome with a dedicated type:

public sealed interface Result<E, A> {

    record Success<E, A>(A value) implements Result<E, A> {
    }

    record Failure<E, A>(E error) implements Result<E, A> {
    }
}

Functional programming calls this a disjoint union or a coproduct type – one of the well-known Algebraic Data Types (ADTs) – which basically means that a Result is either a Success or a Failure. If you’ve worked with Vavr and their Either, this is precisely the same thing under another name.

Have you noticed the sealed keyword in the interface declaration? In a moment you’ll see how it makes the compile-time exhaustiveness check possible in pattern matching.

And what about the error type E in our Result? You could put something from the Throwable hierarchy there, but let’s set exceptions aside for now and add one more coproduct type to represent errors:

public sealed interface Error {

    record UserNotFound(String userName) implements Error {
    }

    record OtherError(Throwable cause) implements Error {
    }
}

Lastly, let’s apply this data model in our business logic, which – to keep things simple – will be a dummy UserService:

public class UserService {

    Result<Error, User> findUser() {
        return new Result.Failure<>(
            new Error.OtherError(new RuntimeException("boom!"))
        );
    }
}

Error handling with switch

Now that the data and business logic are modeled this way, let’s deal with the different possible results of findUser() – with pattern matching, naturally.

A successful result can be matched like so:

switch (userService.findUser()) {
    case Result.Success<?, User> success ->
        System.out.println(STR."User name is \{success.value().name()}");
}

Curious what STR is? Check out string templates (bear in mind they are a preview feature).

The first thing you’ll notice about this code is that it doesn’t compile – which, luckily, is what we expect. You’ve only handled the success case in the pattern matching, yet there’s a failure scenario too, and the compiler is aware of it. How is it aware?

The answer is the sealed keyword in the declaration of the Result interface, which here tells the compiler that every implementation of Result lives in the same file as Result itself. Were you to define anything that implements Result in another file, the compiler would complain (the permits keyword lets you get around this – read more about sealed type hierarchies here). In any case, the key point is that the compiler knows (at compile time, naturally) whether every possible case has been handled, and it will let you know if some aren’t (just as in the enum example at the start).

Once an error case is added, the code compiles:

switch (userService.findUser()) {
    case Result.Success<?, User> success ->
        System.out.println(STR."User name is \{success.value().name()}");
    case Result.Failure<Error, ?> _ ->
        System.out.println("Something went wrong");    
}

Observe that the Failure object instance is ignored – this is done with _, i.e. the unnamed pattern, which is still in preview. Without preview features enabled, you have to put a valid identifier in its place and simply never use it. A single underscore (_) isn’t a valid identifier in non-preview Java 21, but a double underscore (__) is, so you can treat the latter as a poor man’s unnamed pattern until the real one leaves preview.

Pattern matching on nested types

The first attempt above leaves room for improvement in two places:

  • getting at the user’s name field in the success case,
  • handling errors in a more fine-grained way (keep in mind that Error comes in several variants).

As pattern matching also handles nested data structures, the success branch can be rewritten as:

case Result.Success(User(var name, _)) -> 
    System.out.println(STR."User name is \{name}");

Matching on a User nested inside a Result.Success lets you extract the name field and use it directly on the right side of the arrow. Note that the unnamed pattern (still a preview feature in Java 21, remember) can also be used to mark a field of a nested object as ignored.

Keep in mind that when you match on a concrete nested type (User), there’s no longer any need to specify the generic types of Result.Success, because the compiler infers them. Likewise, just as in the earlier Point example, the field types of the User record were inferred as well, which is why var name works.

when conditions behave just as you’d expect, for instance:

case Result.Success(User(var name, var age)) when age > 18 ->
    System.out.println(STR."\{name} is an adult");

For the failure case, so far you’ve only matched on Error, which sits at the top of the error hierarchy. Nothing stops you, however, from being more precise and matching on individual errors – which, after all, are simply nested records:

case Result.Failure(Error.UserNotFound(var name)) ->
    System.out.println(STR."User \{name} not found");
case Result.Failure(Error.OtherError(var cause)) ->
    System.out.println(STR."Other error: \{cause.getMessage()}");

Notably, the exhaustiveness check keeps working as expected even with nested records. Were you to comment out the first case above, the compiler would still detect that only Result.Failure(Error.OtherError) is matched and that a failure with UserNotFound is left unhandled. Once more, a compile-time guarantee that every possible case is handled is enormously helpful.

Summary

This article gave you a refresher on how the switch statement has developed. Since Java 14 it has been an expression that yields a value, relies on the “arrow labels” syntax together with yield, doesn’t fall through by default, and verifies at compile time that every possible case is handled.

You also saw how pattern matching lets you check whether objects have the expected structure – including a built-in way to avoid NullPointerExceptions through the null label – and how to pull data out of that structure, with the compiler inferring the types for you.

Lastly, you learned how to get the most out of all this to do fine-grained pattern matching on a sealed hierarchy of coproduct types (one of the Algebraic Data Types) built from nested records and the sealed keyword.

How do you feel about the new capabilities switch has just acquired? Feel free to reach out with any questions!

The official documentation is available in Java Language Updates, in particular the chapters on switch expressions and pattern matching.