CodeBlanks Logo Icon CodeBlanks

Pattern matching

Learn type conversion with instanceof pattern matching.

Type checking with instanceof

Sometimes you need to know the actual type of a polymorphic reference. The instanceof operator does this: if (s instanceof Circle) is true when s is really a Circle. In older Java you had to cast and store a separate variable.

Since Java 16, pattern matching for instanceof exists: if (s instanceof Circle c) automatically casts s to Circle as c. It is shorter and safer.

Switch patterns (Java 21)

Since Java 21, switch expressions can test types. Writing switch (s) { case Circle c -> ...; case Square q -> ...; } runs different code for each type. This is more readable than a chain of if-instanceof.

The switch expression can return a value; case null handles null. If subclasses are not all covered, a default is required.

Practice Print a field with pattern matching

Use the abstract class Shape and Circle extends Shape from above. Add class Square extends Shape with int side, a constructor and an area method returning side * side. In main, assign Shape s = new Circle(3);, then use if (s instanceof Circle c) pattern matching to print System.out.println("Circle: " + c.r);.

Starter code

Main.java
// abstract Shape and Circle as above

// Add Square class: side field and area method

// main: assign a Circle instance as Shape and print via pattern matching

Sample solution

Main.java
abstract class Shape {
    abstract int area();
}

class Circle extends Shape {
    int r;
    Circle(int r) { this.r = r; }
    int area() { return r * r * 3; }
}

class Square extends Shape {
    int side;
    Square(int side) { this.side = side; }
    int area() { return side * side; }
}

public class Main {
    public static void main(String[] args) {
        Shape s = new Circle(3);
        if (s instanceof Circle c) {
            System.out.println("Circle: " + c.r);
        }
    }
}

Expected output

Circle: 3

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the pattern matching

Question
if (s instanceof ____ c) {
    System.out.println(c.r);
}
Answer
if (s instanceof Circle c) {
    System.out.println(c.r);
}

Explanation: Pattern matching binds c as a Circle.

2 What does instanceof Circle c do?

  • Casts c to Circle and defines it in scope Correct answer
  • Makes c a static variable
  • Removes the Circle class
  • Converts Shape into Circle

Explanation: If the type check passes, pattern matching binds c as Circle.

3 Match the instanceof concepts

Term Meaning
instanceof Type check operator
pattern matching Binds the cast automatically
switch (Java 21) Type-based branching
default Required when not all types covered

All lessons in Intermediate