0Pricing
Java Academy · Lesson

Pattern Matching for instanceof

Bind a variable while testing type.

Pattern Matching for instanceof is a free Java Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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());
        }
    }
}

The New Form

A type pattern declares the variable inline: if (obj instanceof String s). When true, s is already the cast value.

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

The Binding Variable

The variable s is called the pattern variable. It is in scope wherever the compiler can prove the pattern matched, which makes the code both shorter and safer.

Using It in Conditions

Within the same if condition you can use the pattern variable after &&, because the match is guaranteed on that branch.

public class Main {
    public static void main(String[] args) {
        Object obj = "developer";
        if (obj instanceof String s && s.length() > 5) {
            System.out.println("Long string: " + s);
        }
    }
}

Negation and Flow Scope

With negation the scope flips intelligently. After if (!(obj instanceof String s)) return;, the variable s is in scope for the rest of the method because the code only continues when the match held.

public class Main {
    static int safeLength(Object obj) {
        if (!(obj instanceof String s)) {
            return -1;
        }
        return s.length();
    }

    public static void main(String[] args) {
        System.out.println(safeLength("abc"));
        System.out.println(safeLength(42));
    }
}

Replacing equals-and-cast

A textbook use is a clean equals override: test the type and bind in one line, then compare fields.

public class Main {
    static final class Point {
        final int x, y;
        Point(int x, int y) { this.x = x; this.y = y; }
        public boolean equals(Object o) {
            return o instanceof Point p && p.x == x && p.y == y;
        }
        public int hashCode() { return x * 31 + y; }
    }

    public static void main(String[] args) {
        System.out.println(new Point(1, 2).equals(new Point(1, 2)));
        System.out.println(new Point(1, 2).equals(new Point(3, 4)));
    }
}

Handling Mixed Types

Chained else if branches with patterns let you dispatch on several possible types cleanly.

public class Main {
    static String describe(Object obj) {
        if (obj instanceof Integer i) {
            return "int " + (i * 2);
        } else if (obj instanceof String s) {
            return "string of length " + s.length();
        } else {
            return "unknown";
        }
    }

    public static void main(String[] args) {
        System.out.println(describe(21));
        System.out.println(describe("hello"));
        System.out.println(describe(3.14));
    }
}

Null Is Never Matched

An instanceof pattern is false for null, just like the classic operator. So the pattern variable is never bound to null, removing a common source of NPEs.

public class Main {
    public static void main(String[] args) {
        Object obj = null;
        if (obj instanceof String s) {
            System.out.println("matched: " + s);
        } else {
            System.out.println("null or not a String");
        }
    }
}

Cleaner, Safer Code

Pattern matching removes the redundant cast, narrows scope so you cannot misuse the variable, and reads almost like English. It is the preferred style in modern Java.

Putting It Together

A small dispatcher that formats different inputs using patterns.

public class Main {
    static String format(Object o) {
        if (o instanceof Double d) return String.format("%.1f", d);
        if (o instanceof Integer i) return Integer.toString(i);
        if (o instanceof String s && !s.isBlank()) return s.trim();
        return "n/a";
    }

    public static void main(String[] args) {
        System.out.println(format(3.14159));
        System.out.println(format(99));
        System.out.println(format("  spaced  "));
        System.out.println(format(null));
    }
}

Quick Check

Test your understanding of instanceof patterns.

Recap

You learned pattern matching for instanceof.

  • It merges the type test and cast into one expression.
  • The pattern variable is scoped to where the match is proven.
  • Patterns are false for null, avoiding NPEs.
  • It simplifies equals overrides and type dispatch.

Frequently asked questions

Is the “Pattern Matching for instanceof” lesson free?

Yes — the full text of “Pattern Matching for instanceof” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Pattern Matching for instanceof”?

Bind a variable while testing type. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Pattern Matching for instanceof” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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