The tip today is about Pattern Matching for instanceof

Before

		if (s instanceof Car){
                    Car car=(Car)s;
                }

So, this is not a new feature, it already exists. But since Java 16, new language enhancements help you to build a better code.

Now, you can do this:

        if (s instanceof Car car){
                    //do something with car
                }

Benefits:

  1. Safer - now you have a compile time check for the cast.
  2. Cleaner - you don’t need to declare the variable outside the if statement.
  3. More readable - you don’t need to cast the variable inside the if statement.

This opens the door to Pattern Matching for switch and for Record Patterns, which are new features in Java 21, but this is a topic for other tips.

Take a look in repo-tip-5 to see a real example of today’s tip.