Bits of Java – Episode 27: What’s new in Java? (continued)

Today we will continue our excursion into some of the newest features of the Java language.

In particular, today is time for Pattern Matching for instanceof. This feature was already introduced with Java 14, with the goal of simplifying one of the most common pattern in Java.

You have surely found yourself many times coding something like this:

namely, you first check with the instanceof operator whether a reference variable is actually an instance of some class or interface, and, if this is true you proceed with the actual casting operation.

Now, with this new Java feature, you can provide a binding variable, to which, if the condition is valid, the original reference variable will be already casted to.

In this case, you do not need to cast animal to Feline, because this is automatically done for you, if the instanceof condition is satisfied!

So, again, we have with this feature an additional help when writing our code, which makes it more concise and avoids repetitions.

That's all for today! Stay tuned for some other new cool features!