Core Java

Java 14: Pattern Matching for instanceof

Java 14 introduces Pattern Matching for instanceof, another preview language feature, that eliminates the need for casts when using instanceof. For example, consider the following code:

1
2
3
4
if (obj instanceof String) {
    String s = (String) obj;
    System.out.println(s.length());
}

This code can now be rewritten as:

1
2
3
if (obj instanceof String s) {
    System.out.println(s.length());
}

As shown above, the instanceof operator now takes a “binding variable” and the cast to String is no longer required. If obj is an instance of String, then it is cast to String and assigned to the binding variable s. The binding variable is only in scope in the true block of the if-statement.

In particular, this feature makes equals methods a lot more concise as shown in the example below:

1
2
3
4
5
@Override
public boolean equals(Object obj) {
  return this == obj ||
    (obj instanceof Person other) && other.name.equals(name);
}

This feature is an example of pattern matching, which is already available in many other programming languages, and allows us to conditionally extract components from objects. It opens the door for more general pattern matching in the future which I am very excited about!

Published on Java Code Geeks with permission by Fahd Shariff, partner at our JCG program. See the original article here: Java 14: Pattern Matching for instanceof

Opinions expressed by Java Code Geeks contributors are their own.

Fahd Shariff

Fahd is a software engineer working in the financial services industry. He is passionate about technology and specializes in Java application development in distributed environments.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button