Enhanced switch expresses branch selection directly against data instead of translating it into an intermediate enum or temporary variable. Java 14 introduced the modern switch foundation; Java 21 added type patterns, while Java 22 supports underscore bindings for matched values that are not needed. section 5.1.2
Map a book directly to its message
A sealed Book hierarchy lets the compiler check that every permitted subtype is handled. The arrow form avoids fall-through and returns the mapping directly: DigitalBook binds a usable digital value, while underscore marks recognized but unused objects. The result is shorter, safer, and closer to the domain than switching on a book format enum. section 5.1.2
public sealed abstract class Book
permits DigitalBook, PocketBook, HardcoverBook {
// ...
}
public final class DigitalBook extends Book {
// ...
}
public final class PocketBook extends Book {
// ...
}
public final class HardcoverBook extends Book {
// ...
}
Use the sealed hierarchy beside the switch to see how permitted subtypes enable exhaustiveness checking. section 5.1.2
Listing 5.2 Selecting a promotional message with Java’s enhanced switch
public String getPromotionalMessage(Book book){
return switch (book) {
case DigitalBook digital -> digital.getDownloadLink();
case PocketBook _ -> "Same book, smaller format!";
case HardcoverBook _ -> "Old-fashioned book…";
};
}
Inspect the complete promotional-message implementation, including arrow syntax, type patterns, bindings, and subtype-specific results. section 5.1.2
Choose enhanced switch when it improves the code rather than merely shortening it:
- Prefer it when branches form a clear mapping from a value to a result. section 5.1.2
- Use pattern matching when type-specific data is needed without explicit casts. section 5.1.2
- Compare it with instanceof pattern matching, and retain the more expressive version that remains widely understood. section 5.2
