SEARCH BY

All

  • All
  • Java8
  • Spring

Pattern Matching for the instanceof Operator in java 14

Post a Comment

Introduction

We can use instanceOf operator to know whether the object is the type of given class. Java 14 has a new feature called as Pattern Matching for intanceOf operator to reduce coding while binding value to the reference variable.
Pattern Matching for instanceOf is a preview feature in java 14

Traditional way of using instanceOf operator, before java 14

if(act instanceOf Account){
Account aObj=new Account();
// additional code here
}
In the above code in line 2 we have created an object for Account class explicitly.

Pattern Matching way in java-14

if(act instanceOf Account aObj){
// additional code here
// you can use aObj with in this if block only
}
You can notice in the body of if block we did not created an object for Account class explicitly, but we done that in the conditional statement of if block in line 1

Pattern matching with and ( && ) operator

if(act instanceOf Account aObj && aObj.accountNo > 2020){
// additional code here
// you can use aObj with in this if block only
}
In the above conditional statement we have used aObj object with and operator to check account number is greater than 2020 to execute code block.

Pattern matching with OR ( || ) operator

Pattern matching for instnaceOf with OR opeartor cannot work( always return an error )
if(act instanceOf Account aObj || aObj.accountNo > 2020){
// this is an error
}
We cannot use OR (||) operator with pattern matching because aObj.accountNo may be true even if instanceOf returns false.
With OR oeprator we cannot use an object created with pattern matching

Pattern matching with negative opearator ( ! )

if(!(act instanceOf Account aObj)){
// here you cannot use aObj
}
// but outside of the if block you can use aObj
 
In the above code we can use aObj beyond if statement which introduced it.

References

https://docs.oracle.com/en/java/javase/14/language/pattern-matching-instanceof-operator.html
jaya
I love software designing, coding, writing and teaching...

Share this article

Related Posts

Post a Comment

Place your code in <em> </em> tags to send in comments | Do not add hyper links in commnet

Close

Subscribe our newsletter for the latest articles directly into your email inbox