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:
- Type Checking and Casting in One Step: No need for an explicit cast.
- Shorter Code: Reduces boilerplate.
- Available Within Scope: The variable is accessible only within the scope of the
if
block where the condition is evaluated astrue
. - 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 toString
in the sameinstanceof
statement. - Within the
if
block, you can directly usestr
as it is guaranteed to be aString
.
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:
- Scope of Variable:
The variable introduced inside theinstanceof
is only accessible inside the block where the condition istrue
. For example:if (obj instanceof String str) { System.out.println(str); // str is available here } // System.out.println(str); // ERROR: str not available here
- Null Safety:
If the object being matched isnull
, theinstanceof
check will returnfalse
, 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!