Open In App

Pattern Matching For instanceof Java 17

Last Updated : 20 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Pre-requisite: instanceof Keyword in Java

In this article, we are going to discuss the enhancement of Java which is the use of pattern matching feature with instanceof keyword. In computer science, pattern matching is the act of checking a given sequence of tokens for the presence of the constituents of some pattern. Generally, we use pattern matching to check/test some data to see if it is a match or not with respect to some particular pattern, as we do in regular expressions. The following JEPs enhanced pattern matching Java feature to be used with instanceof operator to make it more short and powerful.

Java 14 (JEP 305)
Java 17 (JEP 394)

Now the question will come to your mind what problem above enhancements will solve? So, The pattern matching for instanceof operator eliminates the boilerplate code to type check and cast to a variable. Let us understand Pattern Matching for instanceof with the help of a few examples and here we will start will the traditional approach of using instanceof keyword.

1. Traditional instanceof keyword

At some point, all of you must have written such a program in which you would be checking what type of object you are dealing with, is it of type A or B? Typically, we might do this with the instanceof operator followed by a cast just like below.

Java




// Java Program to Illustrate instanceof Keyword
  
interface Animal {
}
  
class Cat implements Animal {
}
  
class Dog implements Animal {
}
  
public class App {
  
    public static void resolveTypeOfObject(Animal animal)
    {
        if (animal instanceof Cat) {
            // Redundant casting
            Cat cat = (Cat)animal;
            // other cat operations
        }
        else if (animal instanceof Dog) {
            // Redundant casting
            Dog dog = (Dog)animal;
            // other dog operations
        }
    }
  
    public static void main(String[] args)
    {
        Animal animal = new Dog();
        resolveTypeOfObject(animal);
  
        animal = new Cat();
        resolveTypeOfObject(animal);
    }
}


Note: Notice that the casting step seems unnecessary because we have already tested for the instance in the if statement. The pattern-matching enhancement tries to avoid this boilerplate code, as shown in the next section.

2. Pattern Matching

Java 14, via JEP 305, brings an enhanced version of the instanceOf keyword that both tests the parameter object and assigns it to a binding variable of the correct type.

Java




// Java Program to Illustrate Pattern matching for
// instanceof Keyword
  
public class GFG {
  
    public static void resolveTypeOfObject(Animal animal)
    {
        if (animal instanceof Cat cat) {
            cat.meow();
            // other cat operations
        }
        else if (animal instanceof Dog dog) {
            dog.woof();
            // other dog operations
        }
    }
  
    public static void main(String[] args)
    {
        Animal animal = new Dog();
        resolveTypeOfObject(animal);
  
        animal = new Cat();
        resolveTypeOfObject(animal);
    }
}


Let’s understand what is happening here. First, it will check the animal type object with the type Pattern Cat object and if it is of the same type then it will assign the object to the cat variable.

Scope of pattern variables: We need to be a little careful about the scope of such pattern variables. Note that the assignment of the pattern variable happens only when the predicate test is true. The variable is available in the enclosing if block, and we cannot access it outside it.

As we can see, the size of the code has been reduced and we don’t even need to typecast again and again. This version of the code is much easier to understand and the readability is greatly improved.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads