VOOZH about

URL: https://www.javacodegeeks.com/2020/04/java-14-pattern-matching-for-instanceof.html

⇱ Java 14: Pattern Matching for instanceof - Java Code Geeks


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.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Thank you!

We will contact you soon.

πŸ‘ Photo of Fahd Shariff
Fahd Shariff
April 15th, 2020Last Updated: April 13th, 2020
0 74 1 minute read

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

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

0 Comments
Oldest
Newest Most Voted
Back to top button
Close
wpDiscuz