JDK new features
JDK 22
JDK 21
Pattern Matching for switch
Previously, switch was very limited: the cases could only test exact equality, and only for values of a few types: numbers, Enum types and Strings.
This feature enhances switch to work on any type and to match on more complex patterns.
These additions are backwards compatible, switch with the traditional constants work just as before, for example, with Enum values:
enum Status { Normal, Deleted }
public int getStatus(Status s) {
return switch(s) {
case Normal -> 0;
case Deleted -> -1;
};
}
However, now it also works with type patterns introduced by JEP 394: Pattern Matching for instanceof:
class Item {}
class Text extends Item {}
class Image extends Item {
public String getImageType() { return "png"; }
}
public void printItem(Item item) {
var msg = switch(item) {
case Text ignored -> "Text";
case Image ignored -> "Image";
default -> "Unknow item";
};
System.out.println(msg);
}
A pattern supports guards, written as type pattern when guard expression:
var msg = switch(item) {
case Text ignored -> "Text";
case Image img when img.size > 1024 -> "Large Image";
case Image ignored -> "Image";
default -> "Unknow item";
};
Similarly to the type patterns in if conditions, the scope of the pattern variables are flow sensitive. Generally it works just as you'd expect, but there are many rules and edge cases involved.
Switch expressions always had to be exhaustive, in other words, they have to cover all possible input types. This is still the case with the new patterns, the Java compiler emits an error when the switch is incomplete.
Switch can now also match null values. Traditionally, when a null value was supplied to a switch, it threw a NullPointerException. For backwards compatibility, this is still the case when there's no explicit null pattern defined. However, now an explicit case for null can be added:
var msg = switch(item) {
// without this, a NullPointerException throws if item is null.
case null -> "Empty";
case Text ignored -> "Text";
case Image img when img.size > 1024 -> "Large Image";
case Image ignored -> "Image";
default -> "Unknow item";
};
JDK 17
JEP 409: Sealed Classes
Sealed Classes have been added to the Java Language. Sealed classes and interfaces restrict which other classes or interfaces may extend or implement them.
Sealed Classes were proposed by JEP 360 and delivered in JDK 15 as a preview feature. They were proposed again, with refinements, by JEP 397 and delivered in JDK 16 as a preview feature. Now in JDK 17, Sealed Classes are being finalized with no changes from JDK 16.
For further details, see JEP 409.[1]