Codectionary / Developer documentation / Java

Pattern Matching for instanceof

Check an object’s type and obtain a safely typed variable in one expression.

What it is and why to use it

An Object reference may hold a String, an integer wrapper or another object. Pattern matching for instanceof tests the runtime type and introduces a variable of that type when the test succeeds. This standard Java 16 feature removes a repeated cast while keeping the type check visible.

How it works

In value instanceof String text, text is available where the compiler knows the match succeeded. The right side of && is such a place because it runs only after the left side is true. A null value never matches an instanceof type pattern.

Common mistakes and limitations

Do not assume the pattern variable exists outside its valid scope or on the unsuccessful branch. This example is instanceof pattern matching, not the later pattern-switch feature.

Try it and keep learning

Save the complete example below as Main.java. With a JDK supporting Java 17, compile using javac --release 17 Main.java, then run java Main from the same directory. These examples need only the standard library and fixed input; they do not require packages, files or network access.

Syntax

if (value instanceof String text && !text.isBlank()) { /* use text */ }

Examples

Pattern Matching for instanceof

Complete Main.java example — Java 17 or later, without preview features.

public class Main {
  public static void main(String[] args) {
    Object value = "  Java  ";
    if (value instanceof String text && !text.isBlank()) {
      System.out.println(text.strip());
    }
    Object missing = null;
    System.out.println(missing instanceof String);
  }
}
  1. The Object reference holds a String, so the pattern binds text to that same String.
  2. Short-circuit && makes text safe to use in isBlank; strip returns Java without edge spaces.
  3. The null reference fails instanceof and prints false. This is useful when handling values whose declared type is broader than their runtime type.
  4. Expected output: Java false

Best practices

  • Prefer a well-typed interface when you control the object model.
  • Use patterns to make necessary runtime type checks explicit.

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading