0Pricing
Java Academy · Lesson

Pattern Matching for instanceof

Bind a variable while testing type.

Pattern Matching for instanceof

The old way to use instanceof was test-then-cast. Pattern matching combines the test and the cast into one step, binding a typed variable when the test passes.

The Old Boilerplate

Classic code checks the type, then casts to a new variable. It is repetitive and easy to get wrong.

public class Main {
    public static void main(String[] args) {
        Object obj = "hello";
        if (obj instanceof String) {
            String s = (String) obj;
            System.out.println(s.length());
        }
    }
}

All lessons in this course

  1. Pattern Matching for instanceof
  2. Record Patterns
  3. Nested Record Patterns
  4. Patterns in switch
← Back to Java Academy