Pattern Matching for Switch and Record Patterns in Java 21

Emilie Robichaud
3 min readSep 14, 2023

With the release of Java 21 right around the corner, let’s talk about some of its powerful new features. Structured concurrency, scoped values, virtual threads, sequenced collections, and generational ZGC are just a few, but I want to focus on two closely related pattern features — pattern matching for switch and record patterns!

Pattern Matching for Switch

Pattern matching for switch was first previewed in JDK 17 and was subsequently refined in JDK 18, JDK 19, and JDK 20. The feature is now finalized and will be included in JDK 21! The main purpose of this feature is to strengthen the expressiveness and applicability of switch statements by allowing patterns to appear in case labels. This addresses one of the main limitations of classic switch statements; only being able to switch on primitive numeric, string, and enum. Let’s look at an example:

public String getAnimalSound(Animal animal) {
if (animal == null) {
System.out.println("Oops! A null animal?");
} else if (animal instanceof Dog) {
Dog dog = (Dog) animal;
return dog.bark();
} else if (animal instanceof Cat) {
Cat cat = (Cat) animal;
return cat.meow();
} else if (animal instanceof Bird) {
Bird bird = (Bird) animal;
return bird.chirp();
}
}

In theory, this would be an excellent use case for switch statements as there are several if-else statements that need to be simplified. But prior to Java 21, type limitations on case labels would prevent us from being able to use switch! Now, the above code can be refactored as follows:

public String getAnimalSound(Animal animal) {
switch (animal) {
case null -> System.out.println("Oops! A null animal?");
case Dog dog -> return dog.bark();
case Cat cat -> return cat.meow();
case Bird bird -> return bird.chirp();
}
}

The ability to switch on any integral primitive or reference type greatly improves the applicability of switch statements. In our example, using a case label with a type pattern handles the casting of animal subtypes for us. Another enhancement to note is the ability to switch on null, as previously a null check would have to be handled outside of the switch statement. Being able to handle the null case inside our switch makes our code safer, cleaner, and more concise.

Record Patterns

Record patterns were first previewed in JDK 19, and were subsequently refined in JDK 20. The feature is now ready for release and will be included in JDK 21! The goal of this new feature is to extend pattern matching to records, allowing for more sophisticated data queries. Let’s look at an example:

public record Dog(String dogBreed, String dogName) implements Animal {}

public void getDogDetails(Animal animal) {
if (animal instanceof Dog) {
Dog dog = (Dog) animal;
String dogBreed = dog.dogBreed();
String dogName = dog.dogName();
System.out.println(dogName + " the " + dogBreed + " is such a good dog!");
}
}

Here we have a record class for Dog with the fields dogBreed and dogName. Prior to Java 21, if we wanted to print out the details for an animal, specifically a dog, we would have to check the object type, cast it, and define new variables to extract the fields we want. With record patterns, the above code can be refactored as follows:

public void getDogDetails(Animal animal) {
if (animal instanceof Dog(String dogBreed, String dogName)) {
System.out.println(dogName + " the " + dogBreed + " is such a good dog!");
}
}

Record patterns enable us to deconstruct record values. In this example, we were able to combine instance checking, type casting, and data extraction, resulting in more succinct code. Note that record patterns also support nested record deconstruction!

This is a sneak peek of a new code kata that is being developed for the BNY Mellon Code Katas repository! The coffee shop kata will teach developers new features in Java 17+ by having them refactor Java 8 code. The kata will be first presented at Grace Hopper Celebration, in a talk titled Java 17 and Beyond: Learning New Java Features with Code Katas, presented by myself and Aqsa Malik.

--

--

Emilie Robichaud

University of Toronto graduate with majors in Computer Science and Mathematics! Always eager to explore more in the world of technology.