How to Use Pattern Matching with instanceof in Java 17

Pattern matching with the instanceof operator was introduced in Java 16 (as a preview feature) and became a standard feature in Java 17. It simplifies the process of type casting when checking an object’s type, making the code shorter and more readable.

Here’s how you can use pattern matching with instanceof in Java 17:

Syntax

With pattern matching, you can directly declare a local variable while checking the type with instanceof. If the condition is true, the variable is automatically cast to the specified type, and you can use it without explicit casting.

if (object instanceof Type variableName) {
   // Use variableName, which is already cast to Type
}

Key Features:

  1. Type Checking and Casting in One Step: No need for an explicit cast.
  2. Shorter Code: Reduces boilerplate.
  3. Available Within Scope: The variable is accessible only within the scope of the if block where the condition is evaluated as true.
  4. Guarded Pattern (Available in Java 20+ – Preview): Introduced later, allowing additional conditions within instanceof.

Example 1: Basic Usage

package org.kodejava.basic;

public class PatternMatchingExample {
   public static void main(String[] args) {
      Object obj = "Hello, Java 17!";

      if (obj instanceof String str) {
         // Type already checked and cast to `String`
         System.out.println("String length: " + str.length());
      } else {
         System.out.println("Not a string.");
      }
   }
}

Explanation:

  • The variable str is declared and automatically cast to String in the same instanceof statement.
  • Within the if block, you can directly use str as it is guaranteed to be a String.

Example 2: Pattern Matching in Loops

package org.kodejava.basic;

import java.util.List;

public class PatternMatchingExample {
   public static void main(String[] args) {
      List<Object> objects = List.of("Java", 42, 3.14, "Pattern Matching");

      for (Object obj : objects) {
         if (obj instanceof String str) {
            System.out.println("Found a String: " + str.toUpperCase());
         } else if (obj instanceof Integer num) {
            System.out.println("Found an Integer: " + (num * 2));
         } else if (obj instanceof Double decimal) {
            System.out.println("Found a Double: " + (decimal + 1));
         } else {
            System.out.println("Unknown type: " + obj);
         }
      }
   }
}

Output:

Found a String: JAVA
Found an Integer: 84
Found a Double: 4.14
Found a String: PATTERN MATCHING

Example 3: Combining && Conditions

You can combine pattern matching with additional conditions:

package org.kodejava.basic;

public class PatternMatchingExample {
   public static void main(String[] args) {
      Object obj = "Hello";

      if (obj instanceof String str && str.length() > 5) {
         System.out.println("String is longer than 5 characters: " + str);
      } else {
         System.out.println("Not a long string (or not a string at all).");
      }
   }
}

Notes:

  1. Scope of Variable:
    The variable introduced inside the instanceof is only accessible inside the block where the condition is true. For example:

    if (obj instanceof String str) {
       System.out.println(str); // str is available here
    }
    // System.out.println(str); // ERROR: str not available here
    
  2. Null Safety:
    If the object being matched is null, the instanceof check will return false, so you don’t have to handle nulls manually.

Benefits:

  • Simplifies code structure.
  • Eliminates the need for verbose casting.
  • Improves readability and reduces errors associated with unnecessary manual typecasting.

Pattern matching with instanceof is now widely used in modern Java. Make sure you’re using JDK 17 or later to take advantage of this feature!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.