Hi all, in this post under Java pattern matching section, I will introduce you to pattern matching and how to use it with instanceof operator.
Please don’t confuse java pattern matching with regex pattern matching
Regex pattern matching checks whether a given text matches a text pattern and may optionally extract parts of the text.
Whereas Java pattern matching checks whether a given object matches a particular type, shape, or structure and if it matches, it binds the value to variables so that the information can be extracted.
Pattern matching covers all three operations i.e., match, bind, and extract.
Java introduced pattern matching starting from Java 16 and with instanceof operator.
Below is an example of how to use pattern matching using instanceof operator
Main class
package core.patternmatching;public class Example1 { public static void main(String[] args) { Object obj = "hello pattern matching"; if(obj instanceof String s) { System.out.println(s); } else { System.out.println("Not of type string"); } }}
In the above code, at line 5, I created an instance of java “Object” class named “obj” and assigned it a text “hello pattern matching”.
At line 7, you see the example of pattern matching with instanceof operator.
In one line it checks whether “obj” is of type String. If yes cast it to String and assign it to variable “s” to extract the text.
So it matches with a particular type and if yes bind it and extract information all in one line.
The instanceof operator supports pattern matching using type patterns.
In this way we can use instanceof operator for pattern matching.