
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Before pattern matching, switch cases supported only simple testing of a selector expression that needs to match a constant value exactly. The Java SE 21 release introduces pattern matching for switch expressions and statements (JEP 441) as a permanent feature. Pattern matching provides us more flexibility when defining conditions for switch selector expressions and cases.
We can use patterns (e.g., Integer i, String s) in case labels. Furthermore, we can use a selector expression of any reference type (e.g., ArrayList, Stack) in addition to the already supported types. Additionally, we can match null in case labels. We can include a when clause after a case label for conditional matching. Further, when we use a when clause it is called guarded pattern matching.
Java SE 24 adds support for primitive type patterns (e.g., int i, long l) in case labels as a Preview language feature.
In this tutorial, we’ll cover how we can use pattern matching in switch. We’ll also explore some switch specifics, like covering all values, ordering subclasses, and handling null values.
We use switch in Java as a control-flow statement to transfer control to one of the several predefined case statements. The switch statement matches the case label depending on the value of the selector expression.
In the earlier versions of Java, the selector expression had to be a number, a string, or a constant. Also, the case labels could only contain constants:
final String b = "B";
switch (args[0]) {
case "A" -> System.out.println("Parameter is A");
case b -> System.out.println("Parameter is b");
default -> System.out.println("Parameter is unknown");
};
In our example, if variable b wasn’t final, the compiler would throw a constant expression required error.
Pattern matching, in general, was first introduced as a preview feature in Java SE 14. Further, a type pattern consists of a type name and the variable to bind the result to. Applying type patterns to the instanceof operator simplifies type checking and casting. Moreover, it enables us to combine both into a single expression:
if (o instanceof String s) {
System.out.printf("Object is a string %s", s);
} else if (o instanceof Number n) {
System.out.printf("Object is a number %n", n);
}
This built-in language enhancement helps us write less code with enhanced readability. Pattern matching for instanceof became a permanent feature in Java SE 16.
Java SE 17 introduced pattern matching for the switch expressions and statements. Subsequently, Java SE 18, 19, and 20 refined it, and Java SE 21 made it a permanent feature.
Let’s look at how we can apply type patterns and the instanceof operator in switch statements. As an example, we’ll create a method that converts different types to double using if-else statements. Our method will simply return zero if the type is not supported:
static double getDoubleUsingIf(Object o) {
double result;
if (o instanceof Integer) {
result = ((Integer) o).doubleValue();
} else if (o instanceof Float) {
result = ((Float) o).doubleValue();
} else if (o instanceof String) {
result = Double.parseDouble(((String) o));
} else {
result = 0d;
}
return result;
}
We can solve the same problem with less code using type patterns in switch:
static double getDoubleUsingSwitch(Object o) {
return switch (o) {
case Integer i -> i.doubleValue();
case Float f -> f.doubleValue();
case String s -> Double.parseDouble(s);
default -> 0d;
};
}
In earlier versions of Java, the selector expression was limited to only a few types; integral primitive types (excluding long), their corresponding boxed forms, enum types, and String. However, with type patterns, the switch selector expression can be of any reference type in addition to the already supported types.
Type patterns help us transfer control based on a particular type. However, sometimes, we also need to perform additional checks on the passed value.
For example, we may use an if statement to check the length of a String:
static double getDoubleValueUsingIf(Object o) {
return switch (o) {
case String s -> {
if (s.length() > 0) {
yield Double.parseDouble(s);
} else {
yield 0d;
}
}
default -> 0d;
};
}
We can solve the same problem using guarded patterns. They use a combination of a pattern and a when clause:
static double getDoubleValueUsingGuardedPatterns(Object o) {
return switch (o) {
case String s when s.length() > 0 -> Double.parseDouble(s);
default -> 0d;
};
}
Guarded patterns enable us to avoid additional if conditions in switch statements. Instead, we can move our conditional logic to the case label.
We can use a primitive type pattern in switch case labels as a preview feature in Java SE 24. For example, we use primitive type patterns along with a guarded pattern:
void primitiveTypePatternExample() {
Random r=new Random();
switch (r.nextInt()) {
case 1 -> System.out.println("int is 1");
case int i when i > 1 && i < 100 -> System.out.println("int is greater than 1 and less than 100");
default -> System.out.println("int is greater or equal to 100");
}
}
We can use a selector expression of any primitive type including type long, float, double, and boolean, as well as the corresponding boxed types.
Let’s now look at a couple of specific cases to consider while using pattern matching in switch.
When using pattern matching in switch, the Java compiler will check the type coverage.
Let’s consider an example switch condition accepting any object but covering only the String case:
static double getDoubleUsingSwitch(Object o) {
return switch (o) {
case String s -> Double.parseDouble(s);
};
}
Our example will result in the following compilation error:
[ERROR] Failed to execute goal ... Compilation failure
[ERROR] /D:/Projects/.../HandlingNullValuesUnitTest.java:[10,16] the switch expression does not cover all possible input values
This is because the switch case labels are required to cover all possible input values; in this example all Object types.
The default case label may also be applied instead of a specific selector type.
When using subclasses with pattern matching in switch, the order of the cases matters.
Let’s consider an example where the String case comes after the CharSequence case.
static double getDoubleUsingSwitch(Object o) {
return switch (o) {
case CharSequence c -> Double.parseDouble(c.toString());
case String s -> Double.parseDouble(s);
default -> 0d;
};
}
Since String is a subclass of CharSequence, our example will result in the following compilation error:
[ERROR] Failed to execute goal ... Compilation failure
[ERROR] /D:/Projects/.../HandlingNullValuesUnitTest.java:[12,18] this case label is dominated by a preceding case label
The reasoning behind this error is that there is no chance that the execution goes to the second case since any string object passed to the method would be handled in the first case itself.
In earlier versions of Java, each passing of a null value to a switch statement would result in a NullPointerException.
However, with type patterns, it is now possible to apply the null check as a separate case label:
static double getDoubleUsingSwitch(Object o) {
return switch (o) {
case String s -> Double.parseDouble(s);
case null -> 0d;
default -> 0d;
};
}
We should note that a switch expression cannot have both a default case and a total type (selector expression type that covers all possible input values) case.
Such a switch statement will result in the following compilation error:
[ERROR] Failed to execute goal ... Compilation failure
[ERROR] /D:/Projects/.../HandlingNullValuesUnitTest.java:[14,13] switch has both a total pattern and a default label
Finally, a switch statement using pattern matching can still throw a NullPointerException.
However, it can do so only when the switch block doesn’t have a null-matching case label.
In this article, we explored pattern matching for switch expressions and statements, a new feature in Java SE 21. We saw that by using patterns in case labels selection is determined by pattern matching rather than a simple equality check. We also discussed the support for primitive type patterns in Java SE 24.
In the examples, we covered how pattern types can be applied in switch statements. Finally, we explored a couple of specific cases, including covering all values, ordering subclasses, and handling null values.
The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.