Pattern matching routes execution from the shape or category of data. It tests a target against a pattern and, on success, makes extracted values available as binding variables. Used with a clear data model, it can keep behavior separate from data while making the decision visible where it matters. section 4.2.2 section 4.4
A pattern has three parts: a predicate, the target it tests, and binding variables produced by a successful test. In Java 21, records can participate in enhanced switch and instanceof expressions. This makes a branch read as a statement about the data it accepts rather than a sequence of manual casts and accessors. section 4.2.2
Route BMI calculation by profile
A BMI category calculation needs different logic for adults and children. Switch on a PhysicalProfile, use a guarded case for an adult profile, and send all other matching profiles to child-specific logic. The profile is both tested and bound as p, so the adult branch can inspect p.age() without a separate cast. A record pattern can go further by binding gender, age, weight, and height directly when the branch needs those components. section 4.2.2
public BmiCategory calculateBmiCategory(PhysicalProfile profile) {
return switch (profile) {
case PhysicalProfile p when p.age().value() >= 18
-> calculateBmiCategoryForAdult(p);
case PhysicalProfile p -> calculateBmiCategoryForChild(p);
};
}
The switch makes the routing rule explicit: an adult profile goes to adult calculation; the remaining profile case goes to child calculation. section 4.2.2
Use pattern matching when explicit data-driven variation improves the story of the code:
- Match a record or type and bind the value needed by the selected branch. section 4.2.2
- Add a guard when a matching shape needs an additional condition, such as an age threshold. section 4.2.2
- Prefer it for limited variation driven directly by data; retain polymorphism when that is the clearer fit. section 4.3
- Choose the construct for readability, safety, or closeness to the domain—not merely because it is shorter. section 5.2
Pattern matching is not a substitute for modeling. Meaningful records, explicit enums, and small domain types make the available cases understandable; matching then routes behavior through those explicit decisions. The practical heuristic is simple: let data shape behavior, but use the most widely understood construct that keeps the decision clear. section 4.4 section 5.2











