Java 16 : Pattern Matching for instanceof Operator

Java 16 : Pattern Matching for instanceof Operator

We have been using the instanceof operator since ages to determine whether a particular Object is of a particular type.

Java came up with the concept of Pattern Matching for instanceof as a proposal/preview in Java 14, which was put for a 2nd preview in Java 15 and finally made available as a feature in Java 16.

The details over the proposal and its finalization can be further referred to from the following location :

https://openjdk.java.net/jeps/394

The relevant documentation can be referenced from the following link:

https://docs.oracle.com/en/java/javase/16/language/pattern-matching-instanceof-operator.html

Pattern matching involves checking whether an object is of a particular type & if yes, then typecast that Object to the specific type and carry out the desired operations.

The new feature for Pattern Matching for the instanceof Operator makes this process more concise by allowing us to declare the variable along with the instanceof operator test.

Let us go over the following code snippet to understand it better :

Sample Code

package com.kapil.java16;

public class InstanceOfPatternMatchingSample {
    public static void main(String[] args) {
        String mySampleStr = "Hello Kaps !";
        testInstanceOfOldWay(mySampleStr);
        testInstanceOfNewWay(mySampleStr);
    }

    private static void testInstanceOfOldWay(Object inputObj) {
        if(inputObj instanceof String) {
            String inputStr = ((String) inputObj);
            System.out.println(inputStr.toUpperCase());
        }
    }

    private static void testInstanceOfNewWay(Object inputObj) {
        if(inputObj instanceof String inputStr) {
            System.out.println(inputStr.toUpperCase());
        }
    }
}

Output :

In the above code snippet we have 2 methods which are doing the same stuff :

  1. testInstanceOfOldWay(Object inputObj)
  2. testInstanceOfNewWay(Object inputObj)

The 1st one is doing the instanceof check using the conventional operator that we have been using so far.

The 2nd one makes use of the new Pattern Matching feature added in Java 16. If we observe with the 2nd implementation at Line Number 18, we are able to both check for a type as well as carry out the variable assignment both at one shot.

One thing to note about this feature is the scope of the variable String inputStr. It is only confined to the if block.

So that’s it for this post. Go ahead and run this piece of code in your favorite java editor.
See you until next time. Happy Learning !

Leave a Reply

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

Back To Top