Contents

Pattern Matching in Java

Introduction

Pattern Matching is a productivity-oriented enhancement to the Java language. Pattern Matching is part of project Amber which consists of many enhancements like record classes, text blocks, etc. Pattern Matching makes programming in Java better by doing conversions (casting) for you, so you don't have to do it.

Pattern Matching with Instanceof

The Instanceof operator is used to determine if an instance is a member of a class or interface at runtime. For example We have an arbitrary object, and we need to know if it is of type String and if it is, we would like to convert it to a String. Most of us programmers on Java 15 or earlier would have created something like the example below.

1
2
3
4
5
Object object = "String value";
if(object instanceof String){
   String newString = (String) object;
   // the rest of your code
}

Pattern matching removes the need for casting at line 4 if we add a name for the variable. In the example below, we added the name of the variable newString after the type we are checking for. The conversion happens behind the scenes, and inside the if block we can immediately use newString.

1
2
3
4
if(object instanceof String newString){
   newString.toLowerCase(); // now you can immediately the string instance
   // the rest of your code
}

Pattern Matching with Switch

Pattern Matching for Switch statements is still in the preview state. This means that it can still change before it is released. This could break your code in later versions of Java if they change how it works.

Instead of creating many if statements to check the type and perform an action based on it. We can use the preview of pattern matching with Switch statements. The example below uses the enhanced Switch statement to perform an action based on the type of obj.

1
2
3
4
5
6
7
switch (obj) {
   case String s -> System.out.println(s.toLowerCase());
   case Long l -> System.out.println(l.doubleValue());
   case Character c -> System.out.println(c.charValue());
   default -> throw new IllegalStateException("Unexpected value: " + obj);

}

Conclusion

In this post, we looked at the new enhancements Project Amber brings to Java with Pattern matching. It gives a nice productivity increase and removes boilerplate code around checking an instance's type and casting it.

Have a question or idea?

Thank you for reading my post. Have any questions about this topic or an idea for a new topic? Please reach out to me on Twitter or send me an email.

If you want to read more about Java when I write about it – you can follow me on Twitter.