Pattern Matching for instanceof (JEP 395)

Java 16 introduced pattern matching for the instanceof operator, which allows you to use patterns to match the type of an object in an instanceof expression. This feature is useful for improving the readability and maintainability of your code, especially when working with complex data structures or objects that have many subtypes.

Here is an example of how to use pattern matching for instanceof in Java:

class Animal {}
class Cat extends Animal {}
class Dog extends Animal {}

Animal animal = new Cat();

if (animal instanceof Cat c) {
  // c is a Cat object
  System.out.println("The animal is a cat");
} else if (animal instanceof Dog d) {
  // d is a Dog object
  System.out.println("The animal is a dog");
} else {
  System.out.println("The animal is something else");
}

In this example, we are using pattern matching to determine the type of the animal object. If the animal object is a Cat, the c variable is declared and initialized with the Cat object, and the first if block is executed. If the animal object is a Dog, the d variable is declared and initialized with the Dog object, and the second if block is executed. If the animal object is neither a Cat nor a Dog, the else block is executed.

Pattern matching for instanceof can be used in a variety of other contexts as well, such as in switch statements, try-with-resources blocks, and Lambda expression