View ToC

Java 14 - Pattern matching in instanceof



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 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