Pattern Matching for instanceof

Type Test + Cast in One Step (Java 16)

Example

The pattern variable is in scope only where the test is true, and can be combined with &&.

public class Main {
    public static void main(String[] args) {
        Object[] values = { "hello", 42, 3.5, java.util.List.of(1, 2), "" };
        for (Object o : values) {
            // Old way:
            // if (o instanceof String) { String s = (String) o; ... }
            if (o instanceof String s && !s.isEmpty()) {
                System.out.println("String of length " + s.length());
            } else if (o instanceof Integer i) {
                System.out.println("Integer doubled: " + i * 2);
            } else if (o instanceof Number n) {
                System.out.println("Other number: " + n.doubleValue());
            } else {
                System.out.println("Something else: " + o);
            }
        }
    }
}

Output

String of length 5
Integer doubled: 84
Other number: 3.5
Something else: [1, 2]
Something else:

Negated Form

if (!(obj instanceof Customer c)) {
    throw new IllegalArgumentException("Customer expected");
}
// c is in scope here, because the method continues only when obj is a Customer
System.out.println(c.name());