Skip to content
Home » How to Use Pattern Matching for instanceof From JDK16

How to Use Pattern Matching for instanceof From JDK16

beverage breakfast brewed coffee caffeine

The new LTS version (version 17) of Java was released in September. And since the previous LTS (version 11), many cool features were added. One of the coolest ones is “Pattern Matching for instanceof“.

Until Java 15, when we checked whether an object is an instance of a particular class, the compiler didn’t infer the variable’s type, even if the object passed the condition. Because of that, we always had to cast after the instanceof check.

If we try to compile the following code without casting:

public class InstanceOfDemo {
    public static void main(String[] args) {
        Number n = 42;
        if (n instanceof Integer) {
            System.out.println(n.compareTo(21));
        }
    }
}

The following error will occur:

InstanceOfDemo.java:6: error: cannot find symbol
            System.out.println(n.compareTo(21));
                                ^
  symbol:   method compareTo(int)
  location: variable n of type Number
1 error
error: compilation failed

That happens because the compareTo method is declared by Integer and not Number.

So, when we cast the variable to Integer, it compiles.

public class InstanceOfDemo {
    public static void main(String[] args) {
        Number n = 42;
        if (n instanceof Integer) {
            System.out.println(((Integer)n).compareTo(21));
        }
    }
}
$ java InstanceOfDemo.java
1

From Java 16 and newer, we don’t need to cast the variable anymore. We just declare a new variable in the instanceof statement.

public class InstanceOfDemo {
    public static void main(String[] args) {
        Number n = 42;
        if (n instanceof Integer i) {
            System.out.println(i.compareTo(21));
        }
    }
}

Note the new variable i in the above snippet.

That’s it! The new feature from Java 16 eliminates the instanceof-and-cast idiom from our code.

If you want to know more about the JEP 394, you can take a look at its page: https://openjdk.java.net/jeps/394

If you have any questions, leave a comment or send me a message on my social media.