Pattern matching

Pattern matching tests a value's type and destructures it in a single step. With instanceof, the variable is already typed in the block; in a switch, each case can be a type pattern, optionally with a when guard, or a record pattern that extracts its components.

Example

if (obj instanceof String s && !s.isEmpty()) {
    System.out.println(s.length());
}

Related concepts

The whole glossary