days
0
-18
0
hours
-1
-7
minutes
-4
-6
seconds
-1
-4
search
Celebrating Java 14

Pattern Matching for instanceof in Java 14

Mala Gupta
java
© Shutterstock / Kirasolly

To celebrate the release of Java 14, here’s a deep dive into Pattern Matching for instanceof in JDK 14. It’s written by Developer Advocate at JetBrains, founder of eJavaGuru.com and Java Champion, Mala Gupta. What a treat!

The usage of instanceof operator works like a charm with Pattern Matching in Java 14. It makes your code simple and concise to write and read.

In this article, I’ll cover what Pattern Matching for instanceof is and how to use it. Let’s get started.

Why do we need Pattern Matching for instanceof?

As a Java developer, you often read or write code that compares a reference variable to a type by using the instanceof operator. If the result is true, the next obvious step is to explicitly cast it to the type you compared it with, to access its members. These steps have an obvious repetition here, like, compare-ifTrue-cast.

Here’s an example of code that doesn’t use Pattern Matching for instanceof:

void outputValue(Object obj) {
    if (obj instanceof String) {            	// comparison
        String s = (String) obj;              	// New variable & explicit casting
        System.out.println(s.toUpperCase());  	// access member
    }
}

Let’s see how Pattern Matching can help remove redundant code.

What is Pattern Matching for instanceof?

Pattern Matching for instanceof in Java 14 introduces a pattern variable with the instanceof operator. If the instanceof condition is true, the pattern variable binds to the variable being compared, avoiding the need for explicit casting to use its members.

In IntelliJ IDEA 2020.1, you can invoke context sensitive actions on the variable s (by using Alt+Enter or by clicking the yellow light bulb) and select ‘Replace ‘s’ with pattern variable’, to use Pattern Matching in Java 14:

java
The preceding action would modify the code as follows:

java
I’ve highlighted the pattern variable s (on line number 5), which is added right after type ‘String’. This saves you from either defining a new variable, or explicitly casting it to String, before you could call the method toUpperCase() on it.

IntelliJ IDEA 2020.1 supports all the new features of Java 14, including Pattern Matching. Participate it its Early Access Program (EAP) and download its Ultimate Edition for free.

SEE ALSO: Java 14: All the new features of JDK 14 as it hits GA

Scope of Pattern variable

The scope of the pattern variable is limited. If you try to access it in the else block, you receive an error:

java
It could be confusing, but if the class PatternMatching defines an instance or static variable with the same name as the pattern variable (‘s’), the preceding code would compile. In this case, ‘s’ in the else block wouldn’t refer to the pattern variable introduced in the if block.

Simplifying conditional expressions

The simplicity of the Pattern Matching could be deceptive. Here’s an example of how a developer might have defined the method equals() to determine equality of instances for their classes:

package com.jetbrains;
public class Keyboard {
    String model;
    double price;

    @Override
    public boolean equals(Object obj){
        if (obj instanceof Keyboard) {
            Keyboard other = (Keyboard) obj;
            if (model.equals(other.model) && price == other.price) {
                return true;
            }
        }
        return false;
    }
}

This is how the method equals() could be simplified by using Pattern Matching for instanceof:

    @Override
    public boolean equals(Object obj){
        return (obj instanceof Keyboard other && 
                model.equals(other.model) && 
                price == other.price);
    }
} 

Similarly, you can use Pattern Matching with instanceof to merge and simplify if statements with the || operator.

SEE ALSO: Java 14 – “It feels like the early days of Java.”

Preview Language Feature

Pattern Matching has been released as a preview language feature in Java 14. With Java’s new release cadence of versions every six months, new language features are released as preview features, which are neither incomplete nor half-baked features. A preview language feature essentially means that even though this feature is ready to be used by developers, its finer details could change in a future Java release – depending on the feedback received on this feature by developers. Unlike an API, language features can’t be deprecated in future. So, if you have any feedback on text blocks, share it on the JDK mailing list (membership required).

A language feature could remain a preview feature for more than one Java release.

If you are using the command prompt, you must enable preview features during compilation and runtime. To compile a class, say, Java14, which uses Pattern Matching with instanceof, use the following command:

javac --enable-preview --release 14 Java14.java

The compiler will warn you that you are using a preview language feature (which is the intent – so that you are aware you’re using a preview feature).

To execute a class, say, Java14, that uses Pattern Matching (or another preview language feature in Java 14), use the following command:

java --enable-preview Java14

To use Pattern Matching in IntelliJ IDEA, please download its latest version (2020.1 EAP) and configure its Project SDK to JDK 14, and ‘Project Language Level’ to ’14 (Preview) – Records, patterns, text blocks’. Project Structure can be accessed using IntelliJ IDEA Menu options:

java

Conclusion

As developers we often use the instanceof operator in our code. Using Pattern Matching with instanceof would make our code concise and simpler to write and easy to read, every day.

If you want to know more about Pattern Matching with instanceof, as well as other Java 14 features, you can take a look at my screencast on Java 14 language features:

Author
Mala Gupta
Mala Gupta works as a Developer Advocate with JetBrains. A Java Champion, she has over 19 years of experience in the software industry as an author, speaker, mentor, consultant, technology leader, and developer. She has been actively supporting Oracle Java certifications as a path to career advancement. Her Java books with Manning Publications, are top-rated for Oracle Certification around the globe. She co-leads Delhi's Java User Group. Director with Women Who Code Delhi, she drives initiatives for diversity advocacy for Women in Technology.

Leave a Reply

avatar
400