In Java 14 instanceof operator to get type test pattern but as a preview feature. Type test pattern has a predicate identifying a type with an individual binding variable.
Syntax
if (obj instanceof String s) { }
Examine the below given example:
ApiTester.java
public class APITester { public static void main(String[] args) { String message = "Welcome to Tutorialspoint"; 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
25 25