Java 16 (JEP 394: Pattern Matching for instanceof)

Dmitry Ermolchik
1 min readMar 22, 2021

--

Java 16 is released. Let’s take a look at some new features for software engineers.

Today let’s try to understand how an improved instance of the operator can help us write more clear and fluent code.

Pattern matching in the JDK 16 will improve live developers who need to work with libraries that provide an Object.class instance as a return value.

Before Java 16, you needed to write code like this to prevent ClassCastException in runtime:

if (<some object instance> instance of String) {
stringProcessingService.proces((String) <some object instance>);
}

This code looks like little bit bulky;

Now with JDK 16, we can use pattern matching in our code:

if (<some object instance> instanceof String str) {
stringProcessingService.proces(str);
}

This code looks more fluent and clear.

Here is a small example how “real code” will look like:

public static void main(String[] args) {

var list = new ArrayList<>();
list.add("Hello world!");

//Without pattern matching
if (list.get(0) instanceof String) {
System.out.println("Value is a String. Length: " + ((String) list.get(0)).length());
}

//With pattern matching
if (list.get(0) instanceof String value) {
System.out.println("Value is a String. Length: " + value.length());
}

}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

No responses yet

Write a response