Pattern Matching for instanceof With Examples
In this article we are going to look at how pattern matching for instanceof works in Java 14. In coding mostly we check for the type of the class and then cast our object to that specific type. Java 14 has made it really easy to do both the operations in one statement through pattern matching.
Let’s see how we used to do the same thing before Java 14.
public class CastingExample { public static void main(String[] args) { Object sport = "Cricket"; if(sport instanceof String) { String temp = (String) sport; System.out.println(temp); } } }
Output
Cricket
Explanation
Above program consists of two steps,
- Checking for type
- Casting to that type
Note: Pattern Matching is a preview feature and it only works with preview mode enabled.
Java 14 way using Pattern Matching
As we saw traditionally we had to do two operations. Now let’s do it in a cleaner way.
public class PatternMatching { public static void main(String[] args) { Object sport = "Cricket"; if(sport instanceof String temp) { System.out.println(temp); } } }
Output
Cricket
Explanation
In Java 14 if we use pattern matching with instance of then there is no need to do casting. Code becomes a lot more cleaner.
Scope in pattern matching
Variable which is used in the if statement is not applicable in the else part. Let’s have a look at the example.
public class PatternMatching { public static void main(String[] args) { Object sport = "Cricket"; if(sport instanceof String temp) { System.out.println(temp); } else { // temp is not accessible here System.out.println("temp variable is not accessible here."); } } }
Output
Cricket
Explanation
Variable temp is not accessible in the else part, because it is not in the scope.
If statement with instance of in Java 14
In Pattern Matching, variable is in scope only when the instance of statement is evaluated to true. If the statement is either not evaluated or evaluated to false then the variable is not in scope.
public class PatternMatchingWithIfStatement { public static void main(String[] args) { Object age = 19; String name = "Sam"; if(name == "Sam" || age instanceof Integer tempAge) { System.out.println("Age is " + tempAge); } } }
This results in compiler error as instanceof is never evaluated due to short circuit nature of || operator.
Let’s have a look at example with && operator. Now we converted || to &&, so instance of is evaluated and hence tempAge is in scope.
Pay special attention to && operator.
public class PatternMatchingWithIfStatement { public static void main(String[] args) { Object age = 19; String name = "Sam"; if(name == "Sam" && age instanceof Integer tempAge) { System.out.println("Age is " + tempAge); } } }
Output
Age is 19
References
https://openjdk.java.net/jeps/305