Pattern Matching and the Java instanceOf Operator

Pattern matching. Image of green tubes in round holes, and a red square that doesn't fit.

As working professionals of any description, we have a responsibility to ourselves, our colleagues and the company that employs us to stay up to date with current developments in our field. This is true whether we are doctors, chemists, engineers, mechanics, marketers, artists, programmers, or whatever other profession jumps to mind.

As Java programmers, we have our work cut out for us. We have to keep up to date with changes and enhancements to the Java language itself, the constantly expanding Java class libraries, the internals of the JVM, the JDK toolkit, as well as a vast array of associated Java technologies and frameworks.

Keep informed with JEP

One of the best places to keep abreast of enhancements to the Java language and JDK is the JEP website. JEP is an acronym for JDK Enhancement Proposal. The website contains a regularly updated list of proposals that detail the long-term roadmap for JDK releases, language enhancements and related technologies.

The work done here is complementary to the Java Community Process (JCP). The JCP is still the governing body for all standard Java SE APIs and related interfaces. If a JEP wants to revise existing standard APIs or define new ones, then the JCP works in parallel to design, review and approve those changes in an existing or new JSR.

The full JEP process is detailed in JEP 1: JDK Enhancement-Proposal & Roadmap Process.

JEPs are numbered and follow a standard template. Once we understand the template, it becomes very easy to see where and whether we can use it.

Understanding the JEP Template

Let’s look at the JEP that is the topic for this week’s tip: JEP394: Pattern Matching for instanceof

From a programming perspective, the first important things to note are the scope, the status, the release and the component. The scope of JEP 394 is SE (i.e., Java Standard Edition), the status is Closed/Delivered (hurray, we can use it now!), the release is 16 (hurray, we can use it if we’ve installed JDK 16 or later), and the component is language (which means it’s a language change or enhancement).

We can also see that this JEP relates to two previous JEPs of the same name: JEP 305 (the first preview delivered in JDK 14) and JEP 375 (the second preview delivered in JDK 1). It’s often useful to read the earlier preview proposals as well.

The body of the JEP usually contains a number of sections, including a summary, history, goals, motivation, description, future work, dependencies and alternatives. Not all sections will be in every JEP.

Pattern Matching For instanceof

Think of the familiar instanceof-and-cast programming idiom:

// Prior to Java 16
if (obj instanceof Person) {
    Person p = (Person)obj;
    // use p here
}

We’re all familiar with this style of code: we first test to see if obj is a Person, then we create a temporary Person variable, cast obj to a Person and assign it to the temporary variable.

This is relatively tedious boilerplate code which slows us down and creates cracks for errors to creep in.

In Java 16, JEP 394 extended the instanceof operator to take a type test pattern instead of just a type. This allows pattern matching, which simplifies the instanceof and cast idiom, making it more concise and less error-prone.

In the following code, Person p is the type test pattern:

// From Java 14/15/16
if (obj instanceof Person p) {
    // use p here
}

Here obj matches the type pattern Person p if the value of obj is an instance of Person at runtime. If the pattern matches, then the instanceof expression is true and the pattern (or binding) variable p is initialized to the value of obj cast to a Person. The binding variable p can then be used in the contained block.

There are some scoping issues:

if (obj instanceof Person p) {
    // can use p here
}
else {
    // cannot use p here
}

The binding variable p is in scope in the true block of the if statement, and not in the false block.

Further Reading and Signing Off

For a deeper dive into instanceof pattern matching, see the description sections of the relevant JEPs.

Was this interesting? Please share your comments.

Leave a Comment

Your email address will not be published. Required fields are marked *

Thank You

We're Excited!

Thank you for completing the form. We're excited that you have chosen to contact us about training. We will process the information as soon as we can, and we will do our best to contact you within 1 working day. (Please note that our offices are closed over weekends and public holidays.)

Don't Worry

Our privacy policy ensures your data is safe: Incus Data does not sell or otherwise distribute email addresses. We will not divulge your personal information to anyone unless specifically authorised by you.

If you need any further information, please contact us on tel: (27) 12-666-2020 or email info@incusdata.com

How can we help you?

Let us contact you about your training requirements. Just fill in a few details, and we’ll get right back to you.