Java 14 introduces instanceof operator to have type test pattern as is a preview feature. Type test pattern has a predicate to specify a type with a single binding variable.
Syntax
if (obj instanceof String s) {
}
Example
Consider the following example −
ApiTester.java
public class APITester {
public static void main(String[] args) {
String message = "Welcome to hitechpoints";
Object obj = message;
// Old way of getting length
if(obj instanceof String){
String value = (String)obj;
System.out.println(value.length());
}
// New way of getting length
if(obj instanceof String value){
System.out.println(value.length());
}
}
}
Compile and Run the program
$javac -Xlint:preview --enable-preview -source 14 APITester.java
$java --enable-preview APITester
Output
23
23