CodeGym /Courses /JAVA 25 SELF /Pattern Matching in switch (Java 17/21+)

Pattern Matching in switch (Java 17/21+)

JAVA 25 SELF
Level 65, Lesson 2
Available

1. Classic Switch: Limitations of the Past

Let’s recall what the switch in Java was like before pattern matching appeared. It was, to be honest, quite conservative. It worked only with primitives (int, char, and later enum, String), and if you wanted to handle different object types, you had to write long if-else chains.

Object obj = ...;
if (obj instanceof String) {
    String s = (String) obj;
    System.out.println("String: " + s);
} else if (obj instanceof Integer) {
    Integer i = (Integer) obj;
    System.out.println("Number: " + i);
} else if (obj == null) {
    System.out.println("null!");
} else {
    System.out.println("Something else");
}

Convenient? Not really. The code is verbose, it’s easy to make mistakes, and if a new type is added, you have to rewrite the if-else chain again.

2. Pattern Matching in Switch: A Revolution in Java 17/21+

Java 17 (preview) and finally Java 21+ introduced a new version of switch that supports pattern matching. Now switch can work not only with primitives but with any objects and types, even with null, and it supports additional conditions (guard expressions).

New Syntax: Concision and Power

An example of simple pattern matching in switch:

Object obj = ...;
switch (obj) {
    case String s -> System.out.println("String: " + s);
    case Integer i -> System.out.println("Number: " + i);
    case null -> System.out.println("null!");
    default -> System.out.println("Something else");
}

What’s happening here?

  • If obj is a string, the variable s is automatically narrowed to type String.
  • If obj is an integer, the variable i becomes an Integer.
  • If obj is null, a special branch is triggered.
  • Everything else — default.

Why is this convenient?

  • No manual casting: Java takes care of type safety for you.
  • Less code: No extra parentheses, casts, or duplication.
  • Safer: The compiler checks that you haven’t forgotten to handle possible cases (especially with sealed classes, which we’ll discuss later).
  • Easy to add new types: Just add another case branch.

3. Pattern Matching in Switch: Basic Examples

Example 1: Handling Different Types

Object obj = 42;

switch (obj) {
    case String s -> System.out.println("String: " + s);
    case Integer i -> System.out.println("Number: " + i);
    case null -> System.out.println("This is null");
    default -> System.out.println("Unknown type");
}

Output:

Number: 42

Example 2: Using Guard Expressions (when)

Sometimes it’s not enough to just know the type — you want to add an additional condition.

Object obj = "Hello, world!";

switch (obj) {
    case String s when s.length() > 10 -> System.out.println("Long string: " + s);
    case String s -> System.out.println("Short string: " + s);
    case Integer i when i > 0 -> System.out.println("Positive number: " + i);
    case Integer i -> System.out.println("Non-positive number: " + i);
    default -> System.out.println("Something else");
}

Output:

Long string: Hello, world!

Note:

  • when is a guard expression, an additional check for a case.
  • If the condition is not met, the next case branches are checked.

Example 3: Handling null

Object obj = null;

switch (obj) {
    case null -> System.out.println("This is null!");
    default -> System.out.println("Not null");
}

Output:

This is null!

4. Pattern Matching in Switch with Classes and Inheritance

Pattern matching in switch works especially well with class hierarchies.

sealed interface Shape permits Circle, Rectangle, Square {}

final class Circle implements Shape {
    final double radius;
    Circle(double radius) { this.radius = radius; }
}

final class Rectangle implements Shape {
    final double width, height;
    Rectangle(double width, double height) { this.width = width; this.height = height; }
}

final class Square implements Shape {
    final double side;
    Square(double side) { this.side = side; }
}
Shape shape = new Rectangle(2, 3);

String description = switch (shape) {
    case Circle c -> "Circle with radius " + c.radius;
    case Rectangle r -> "Rectangle " + r.width + "x" + r.height;
    case Square s -> "Square with side " + s.side;
};
System.out.println(description);

Output:

Rectangle 2.0x3.0

Nice: If you use sealed classes and handle all of their variants, a default branch is not required — the compiler understands there can be no other options!

5. Using Switch with Record Classes and Nested Patterns

Pattern matching in switch supports working with record classes and nested patterns (starting with Java 21+).

record Point(int x, int y) {}
record Line(Point start, Point end) {}

Object obj = new Line(new Point(1, 2), new Point(3, 4));

String result = switch (obj) {
    case Line(Point(int x1, int y1), Point(int x2, int y2)) ->
        "Line from (" + x1 + "," + y1 + ") to (" + x2 + "," + y2 + ")";
    case Point(int x, int y) -> "Point (" + x + "," + y + ")";
    default -> "Unknown object";
};
System.out.println(result);

Output:

Line from (1,2) to (3,4)

6. Features and Limitations of Pattern Matching in Switch

Variables Are Available Only Inside a Case

A variable declared in a pattern (for example, String s) exists only inside the corresponding case block. Outside of it, the variable is not accessible.

switch (obj) {
    case String s -> System.out.println(s); // s is visible here
    // System.out.println(s); // compilation error here!
}

Handling null

  • In the old object-based switch, attempting to pass null would result in a NullPointerException.
  • In the new pattern-matching switch, you can explicitly handle null with case null.

Guard Expressions (when)

Additional conditions (when) are available only in the expression-style switch (arrow syntax ->).

case String s when s.isEmpty() -> System.out.println("Empty string");

JDK and IDE Requirements

  • Pattern matching in switch is a Java 17 (preview) feature and Java 21+ (stable).
  • You need JDK 21 and an IDE that supports the new features (for example, IntelliJ IDEA 2023+).

7. Applying the Pattern-Matching Switch in a Real Application

Let’s look at a sample app — a simple task tracker. Suppose you have an abstract task type and its different kinds:

sealed interface Task permits SimpleTask, DeadlineTask, MeetingTask {}

final class SimpleTask implements Task {
    final String description;
    SimpleTask(String description) { this.description = description; }
}

final class DeadlineTask implements Task {
    final String description;
    final java.time.LocalDate deadline;
    DeadlineTask(String description, java.time.LocalDate deadline) {
        this.description = description;
        this.deadline = deadline;
    }
}

final class MeetingTask implements Task {
    final String topic;
    final java.time.LocalTime time;
    MeetingTask(String topic, java.time.LocalTime time) {
        this.topic = topic;
        this.time = time;
    }
}

All logic in one compact switch:

Task task = new DeadlineTask("Submit the project", java.time.LocalDate.of(2024, 7, 1));

String info = switch (task) {
    case SimpleTask st -> "Regular task: " + st.description;
    case DeadlineTask dt -> "Task with a deadline: " + dt.description + ", due by " + dt.deadline;
    case MeetingTask mt -> "Meeting: " + mt.topic + " at " + mt.time;
};
System.out.println(info);

Output:

Task with a deadline: Submit the project, due by 2024-07-01

8. Common Mistakes When Using Pattern Matching in Switch

Mistake #1: Forgot to handle null. If you didn’t add case null and obj can be null, you’ll get a MatchException (or NullPointerException in older switch). Always handle null explicitly when possible.

Mistake #2: Didn’t account for all subclasses of a sealed class. If you use a sealed class and don’t handle all variants in the switch, the compiler will report an error or require a default branch. Don’t forget to add new case branches when extending the hierarchy.

Mistake #3: The pattern variable is not available outside the case block. A variable declared in a pattern exists only inside the arrow block. Trying to use it outside that block will cause a compilation error.

Mistake #4: Using new features on an old JDK or in an old IDE. Pattern matching in switch requires Java 21+ and proper support in your IDE. If you use an older version, you’ll get a compilation error or incorrect hints.

Mistake #5: Confusion with guard expressions. Trying to use when in an old block-style switch? Won’t work. Guards are available only with the arrow syntax ->.

Mistake #6: Forgot the default branch when working with open hierarchies. If your switch operates not only on sealed classes, be sure to add default — otherwise not all cases will be handled.

1
Task
JAVA 25 SELF, level 65, lesson 2
Locked
Number Classifier for Analytics System 🔢
Number Classifier for Analytics System 🔢
1
Task
JAVA 25 SELF, level 65, lesson 2
Locked
Smart Pet Identification System for a Veterinary Clinic 🐕🐈🦜
Smart Pet Identification System for a Veterinary Clinic 🐕🐈🦜
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION