Pattern Matching in Java 16

Will
1 min readMay 14, 2021

--

In this article I’m gonna write everything you need to know about the pattern matching for instanceof which is introduced in java 16. Let’s start.

Environment setup

Download and install jdk16 here. Verify in command line javac -version .

Preparation

We prepare a simple interface Animal and two classes Bird And Dog which implement the interface.

interface Animal {

}

private static class Bird implements Animal {
public void fly() {
System.out.println("Flying");
}
}

private static class Dog implements Animal {
public void bark() {
System.out.println("Barking");
}
}

And let’s define two animals for test:

Animal animal1 = new Bird();
Animal animal2 = new Dog();

The old way

animal1 has to be casted to Bird in the if condition in order to call the specific fly method and same for animal2 .

if (animal1 instanceof Bird) {
((Bird) animal1).fly();
}
if (animal2 instanceof Dog) {
((Dog) animal2).bark();
}

The new way

Given the fact that the type of an animal has already been determined by instanceof in if condition, we can directly match the pattern by adding a variable bird with type Bird and use if within the if block.

if (animal1 instanceof Bird bird) {
bird.fly();
}
if (animal2 instanceof Dog dog) {
dog.bark();
}

And this won’t be triggered of course.

if (animal1 instanceof Dog dog) {
dog.bark();
}

Yes that’s it! A simple and convenient syntax sugar. Enjoy.

PS: You can find all the code samples here.

--

--

Will
Will

Written by Will

A full stack(overflow) developer

No responses yet