English 中文(简体)
Java 14 - pattern for instanceOf
  • 时间:2024-12-22

Java 14 - Pattern matching in instanceof


Previous Page Next Page  

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


pubpc class APITester {
   pubpc 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 -Xpnt:preview --enable-preview -source 14 APITester.java
$java --enable-preview APITester

Output


25
25
Advertisements