Java 14 new feature with pattern matching for the instanceof operator(preview)

Murali krishna Konduru
3 min readSep 17, 2020

What is the preview feature?

Preview feature is ready to be used by developers, although its finer details could change in the future Java release depending on developer feedback. It means this feature may exist in different form or not at all exist in future JDK releases.

To compile a source file with pattern matching for instanceof, you must use the options -enable-preview and -release 14. Here is an example to compile a source file called TestInstanceOfOperator.java from the command line.

javac --enable-preview --release 14 TestInstanceOfOperator.java

In Java instanceof keyword is a binary operator, used to check whether the object belongs to the particular type of class, subclass, or interface.

package com.java.test;
public class TestInstanceOfOperator {
public static void main(String[] args) {
String s = “test”;
if (s instanceof String) { -----------------> (1)
String s1 = (String) s; ---------------> (2)
System.out.println(s1.toUpperCase()); -> (3)
}
}
}

In the above code, we can observe 3 things: 1) Type checking 2) Typecasting to target object 3) Extracting the required data from the target object.

Enabling Preview feature in Eclipse.

Enable Preview feature in Eclipse

Pattern Variables:

Pattern variables are declared implicitly as final. we can not assign any value to a pattern variable since it is final. Java 14 simplifies the usage of instanceof operator to make developer code safer and simpler to write.

package com.java.test;public class TestInstanceOfOperator {
public static void main(String[] args) {
String str = “test”;
if(str instanceof String s1) {
System.out.println(s1.toUpperCase());
}else{
//we can't use s1 here since it is implicitly final
System.out.println(s1.toUpperCase());
}
}
}

When a preview feature is used in the code, the compiler provides a default warning that the preview feature may not be supported in a future release. You can ignore the warning or set it to Info by changing its severity level in eclipse properties.

Warning message in Eclipse

What if the target object is null.

If the target object is null, the instanceof operator behavior is the same as the earlier java versions. if the pattern will only match then only the next line of code will be executed.

Working with the equals() method.

@Override 
public boolean equals(Object obj) {
return (obj instanceof Person) &&
((Persion) obj).firstName.equalsIgnoreCase("Sam");
}

The same code will be written as follows in using type test pattern:

@Override public 
boolean equals(Object obj) {
return (obj instanceof Persion p) &&
p.firstName.equalsIgnoreCase("Sam");
}

conclusion:

This feature embrace developer’s to write crisp code, less boilerplate code, also it reduces the number of object castings. It will be much helpful while using the equals() method.

--

--