Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

instanceof — type patterns and flow scoping

The instanceof operator tests an object's compatibility with a type and returns boolean. A type pattern can also declare a variable available wherever the compiler can prove that matching succeeded. For null, the result is false.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

expression instanceof ReferenceType
expression instanceof ReferenceType variable

instanceof is a keyword used as an operator. In Java SE 21, its left operand must have a reference type or the null type. The form value instanceof String checks whether a non-null reference could be cast to String without ClassCastException; the result is boolean. The test includes compatible subtypes and interface implementations, not only an exact class. For null, it returns false.

A type pattern, such as value instanceof String text, combines the test with the declaration of a variable text of type String. On a match, it refers to the same object, so no explicit cast is needed. Tests disallowed by the operand types are compilation errors, not simply tests that return false.

Flow scoping makes scope depend on control flow: the variable is available wherever the compiler can prove that the pattern matched. In value instanceof String text && text.length() > 3, the right side of && runs only after a successful test. By contrast, value instanceof String text || text.isEmpty() does not compile: its right side may run after matching failed.

A pattern variable's scope can extend past the if statement. After if (!(value instanceof String text)) { return 0; }, text is available in subsequent statements of the same enclosing block because return exits the method if the pattern does not match. In the example, the if is directly in the method body. If the guard is inside a nested block, text is not available outside that block. The example also demonstrates && and the behavior for another type and null.

Examples

public class Main {
    static int lengthOrZero(Object value) {
        if (!(value instanceof String text)) {
            return 0;
        }
        return text.length();
    }

    public static void main(String[] args) {
        Object value = "Java";
        if (value instanceof String text && text.length() > 3) {
            System.out.println(text.length());
        }
        System.out.println(lengthOrZero("OK"));
        System.out.println(lengthOrZero(42));
        System.out.println(lengthOrZero(null));
    }
}

Result

4
2
0
0

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources