Part 14 / Stage 3
Modern Java and pattern matching
Goal: Model a closed set of types with
sealed, replace a cast withinstanceofpattern matching, write an exhaustive pattern-matchingswitchover that sealed hierarchy (type patterns, guards, record patterns), and know what actually changed between Java 17 and 21. Time: ~5 hours
What you will learn
sealedclasses and interfaces:permits, and whatfinal/sealed/non-sealedeach commit a subtype to- Pattern matching for
instanceof(JEP 394): test and bind in one step, including guarded patterns - Pattern matching for
switch(JEP 441): type patterns, guards withwhen,case null, and exhaustiveness without adefault - Record patterns (JEP 440): deconstructing a record's components directly in
instanceoforswitch, nested - Records, recapped: compact constructors, static factories, and why every permitted type in this part is a record
- What changed Java 17 → 21, and which of today's keywords were previews before they were final
- Putting it together: route webhook-style events with a pattern-matching
switch
About "JDK 21.0.11 Corretto": every command and output below was run on the exact JDK pinned in
../../TOOLING.md. Pattern matching and sealed types are stable, finalized language features as of Java 21 — nothing here is a preview feature on this JDK.
Topics in this part
Practice
Try each one yourself first. Then check the solution.
Every exercise is one .java file with a public static void main(String[] args) method. solutions/ex01.java through ex08.java use a non-public top-level class (class Ex01 { ... }, matching the stage-wide convention from Part 1) so the filename does not need to match the class name.
Exercise 1: A sealed discount-rule hierarchy for a Diwali sale
Scenario: An online store applies exactly one of three kinds of discount rule to an order total: a flat amount off, a percentage off, or no discount. What to do:
- Write
sealed interface DiscountRule permits FlatDiscount, PercentDiscount, NoDiscountRule, with recordsFlatDiscount(long amountPaise),PercentDiscount(double percent),NoDiscountRule(). - Write
finalPricePaise(long originalPaise, DiscountRule rule)using aninstanceof+ cast chain (no pattern matching yet) that subtracts the flat amount (never below zero), applies the percentage, or returns the original price unchanged. - For an original price of Rs 1500.00 (
150000paise), print the final price for each of the three rules (FlatDiscount(20000),PercentDiscount(10.0),NoDiscountRule()).
Sample output:
FlatDiscount[amountPaise=20000] -> Rs 1300.00
PercentDiscount[percent=10.0] -> Rs 1350.00
NoDiscountRule[] -> Rs 1500.00
💡 Hint: Math.round(originalPaise * (1 - percent / 100.0)) applies a percentage without a separate rounding step; Math.max(0, ...) keeps a flat discount from pushing the price negative.
Exercise 2: Refactor a notification sender to pattern-matching instanceof
Scenario: A notification sender currently uses instanceof + cast for three channels; rewrite it with pattern matching, and add one guarded pattern.
What to do:
- Write
sealed interface Notification permits SmsNotification, EmailNotification, PushNotification, with recordsSmsNotification(String phone, String text),EmailNotification(String address, String subject),PushNotification(String deviceToken, String text, int priority). - Write
send(Notification notification)using pattern-matchinginstanceof(test and bind in one step) for all three, returning a one-line description for each. - Write
urgency(Notification notification): a guarded patternnotification instanceof PushNotification push && push.priority() >= 8returning"URGENT push (priority <n>)"; otherwise, if it's still a push notification,"normal push (priority <n>)"; otherwise"not a push notification". - Call
sendon one of each notification type, then callurgencyon an SMS, a low-priority push (3) and a high-priority push (9).
Sample output:
SMS to 9876543210: Your OTP is 4821
Email to [email protected], subject: Order shipped
Push to device-101: Weekly summary ready
Push to device-102: Payment failed, action needed
not a push notification
normal push (priority 3)
URGENT push (priority 9)
💡 Hint: the guarded case must come before the unconditional "still a push" case, or the guard never gets a chance to run.
Exercise 3: Loan decisions, with a guard that escalates large amounts
Scenario: A loan system's decision is Approved, Rejected, or PendingReview; a large approved amount needs an extra sign-off message.
What to do:
- Write
sealed interface LoanDecision permits Approved, Rejected, PendingReview, with recordsApproved(String applicant, long amountPaise, double interestRatePercent),Rejected(String applicant, String reason),PendingReview(String applicant, String missingDocument). - Write
message(LoanDecision decision)as a pattern-matchingswitch, nodefault: anApprovedcase guarded withwhen amountPaise() >= 10_00_000_00L(Rs 10,00,000 or more) returns a sign-off message; the unconditionalApprovedcase returns the amount and interest rate;Rejectedreturns the reason;PendingReviewreturns the missing document. - Print the message for one small approval, one large approval, one rejection, one pending review.
Sample output:
Ravi Shah: approved, Rs 5000 at 9.5% interest
Meera Iyer: approved for a large amount, needs branch manager sign-off before disbursal
Arjun Nair: rejected (credit score below threshold)
Asha Kulkarni: pending, missing income proof
💡 Hint: put the guarded Approved case before the unconditional one -- same type, so order decides which one actually gets checked first.
Exercise 4: A Tatkal seat allocation that might not exist yet
Scenario: A booking's seat-allocation field is null before allocation, an Integer waitlist position, or a String seat number -- RAC seats need calling out separately.
What to do:
- Write
seatStatus(Object allocation)as a pattern-matchingswitchwith an explicitcase nullreturning"not yet allocated, check again closer to departure". - Handle
Integerwith a guardwhen position <= 5("likely to confirm") versus the unconditional case ("unlikely to confirm"). - Handle
Stringwith a guard for one starting with"RAC"versus a plain confirmed seat. - Add a
defaultfor anything else. - Call it with
null,3,42,"RAC-12","B4-22", and7.5(a value matching none of the typed cases), printing each result.
Sample output:
not yet allocated, check again closer to departure
waitlisted at #3, likely to confirm
waitlisted at #42, unlikely to confirm
RAC seat, shared berth: RAC-12
confirmed seat: B4-22
unrecognized allocation value: 7.5
💡 Hint: case null -> must be written as its own case; a switch on a possibly-null subject with no case null still throws NullPointerException, Java 21 or not.
Exercise 5: An order's shipping summary, three levels deep
Scenario: An order's shipping label needs the customer's name and the full address, including the pincode's state -- and a high-value Maharashtra order needs flagging for priority dispatch. What to do:
- Write records
Pincode(String code, String state),Address(String line1, String city, Pincode pincode),Customer(String name, String phone),Order(String id, Customer customer, Address address, long totalPaise). - Write
shippingSummary(Object maybeOrder): a record patterninstanceofdeconstructingOrderthree levels deep (down toPincode'scodeandstate) with a guardstate.equals("Maharashtra") && totalPaise >= 5_00_000Lprinting a"PRIORITY DISPATCH"line; otherwise a plain summary line; otherwise (not anOrderat all)"not an order". - Build three orders (two in Maharashtra, one of them over Rs 5,000 and the other not quite; one in Gujarat) and print
shippingSummaryfor each, plus one call with a plainStringinstead of anOrder.
Sample output:
ORD-9001: PRIORITY DISPATCH -- Asha Kulkarni, Pune - 411005 (Maharashtra), Rs 6500
ORD-9002: Ravi Shah, Ahmedabad - 380001 (Gujarat), Rs 6500
ORD-9003: Meera Iyer, Mumbai - 400001 (Maharashtra), Rs 1200
not an order
💡 Hint: the guard goes after the whole record pattern, as &&, same as a guarded instanceof -- maybeOrder instanceof Order(...) && state.equals(...).
Exercise 6: Add a case, watch the compiler catch the gap
Scenario: Vehicle starts out sealed over Bike and Car only, with a switch computing a toll fee for each. Adding a third vehicle type without updating that switch should not compile.
What to do:
- Write
sealed interface Vehicle permits Bike, Carwith recordsBike(String reg)andCar(String reg), andtollFeePaise(Vehicle vehicle)as aswitchwith exactly those two cases (Bike→0L,Car→6_500L), nodefault. - Compile it. It should succeed.
- Add
Bus(String reg, int seatingCapacity)toVehicle'spermitslist and as a new record, without touchingtollFeePaiseyet. Recompile, and read the error. - Now fix
tollFeePaise: add a case forBus, guarded so aBuswithseatingCapacity() > 40costs more than a smaller one. - Run the fixed version against one
Bike, oneCar, and twoBuses (one over 40 seats, one under), printing the toll for each.
The real compile error from step 3 (captured directly, on this course's pinned JDK, from a scratch file with just Bike/Car handled and Bus added to permits; not part of solutions/ since it's deliberately broken):
$ javac Ex06Broken.java
Ex06Broken.java:8: error: the switch expression does not cover all possible input values
return switch (vehicle) {
^
1 error
Sample output (fixed version, step 5 — this is solutions/ex06.java):
Bike[reg=MH12AB1234] -> toll Rs 0
Car[reg=MH12CD5678] -> toll Rs 65
Bus[reg=MH12EF9012, seatingCapacity=50] -> toll Rs 220
Bus[reg=MH12GH3456, seatingCapacity=30] -> toll Rs 150
💡 Hint: this is the entire point of sealing Vehicle in the first place -- the compiler, not a code reviewer, is the one that notices the new Bus case went unhandled.
Exercise 7: A second webhook router, for order events
Scenario: An e-commerce platform's own webhook: orders are placed, shipped, cancelled, or refunded -- the same shape as the part's WebhookEventRouter, built again from scratch for a different domain.
What to do:
- Write
sealed interface OrderEvent permits OrderPlaced, OrderShipped, OrderCancelled, PaymentRefunded, with recordsOrderPlaced(String orderId, long totalPaise),OrderShipped(String orderId, String courier, String trackingId),OrderCancelled(String orderId, String reason),PaymentRefunded(String orderId, long amountPaise). - Write
route(OrderEvent event)as one exhaustive, record-deconstructingswitch, nodefault:OrderPlacedguardedwhen totalPaise >= 50_000_00L(Rs 50,000+) routes to a warehouse stock-check message; the unconditional case routes to a plain pack message.OrderShippedroutes to a customer notification with courier and tracking id.OrderCancelledguardedwhen reason.equals("OUT_OF_STOCK")routes to a warehouse restock alert; the unconditional case routes to support.PaymentRefundedroutes to a ledger message.
- Route a list covering every case (including both branches of both guards) and print each result.
Sample output:
WAREHOUSE ORD-8001: pack order, Rs 1499
WAREHOUSE ORD-8002: high-value order (Rs 75000), verify stock before packing
NOTIFY ORD-8001: shipped via BlueDart, tracking BD1234567890
WAREHOUSE ORD-8003: cancelled (out of stock), trigger restock alert
SUPPORT ORD-8004: cancelled (CUSTOMER_REQUEST)
LEDGER ORD-8003: refunded Rs 2999
💡 Hint: this is structurally identical to examples/WebhookEventRouter.java -- same shape (sealed interface of records, one guarded exhaustive switch), different domain and field names.
Exercise 8 (stretch): A two-level sealed hierarchy, one flat switch
Scenario: A parking system's Vehicle is either a TwoWheeler or a FourWheeler -- and each of those is itself sealed over the real vehicle types. One switch over the four leaf types should still be exhaustive for Vehicle, with no default.
What to do:
- Write
sealed interface Vehicle permits TwoWheeler, FourWheeler,sealed interface TwoWheeler extends Vehicle permits Bike, Scooter,sealed interface FourWheeler extends Vehicle permits Car, Van. - Write records
Bike(String reg),Scooter(String reg),Car(String reg, int seats),Van(String reg, double cargoCubicMeters)implementing the right interface each. - Write
parkingSlot(Vehicle vehicle)as oneswitchover all four leaf types directly (not overTwoWheeler/FourWheeler), nodefault:Bike/Scootergo to a two-wheeler slot;Carguardedwhen seats() > 5goes to a large four-wheeler slot, otherwise standard;Vangoes to a loading-bay slot. - Confirm it compiles with no
defaulteven thoughBike/Scooter/Car/Vansit two levels belowVehicle, then run it against one of each (twoCars: one 5-seater, one 7-seater).
Sample output:
two-wheeler slot (bike): MH12AB1234
two-wheeler slot (scooter): MH12CD5678
standard four-wheeler slot: MH12EF9012
large four-wheeler slot: MH12GH3456
loading-bay slot: MH12IJ7890 (4.5 m3)
💡 Hint: the compiler walks the whole sealed tree, not just one level -- it can prove Vehicle = TwoWheeler | FourWheeler = (Bike | Scooter) | (Car | Van), so a switch naming all four leaves already covers every Vehicle.
Show the solutions for Part 14 (8 files)
solutions/ex01.java
// Exercise 1: a sealed discount-rule hierarchy for a Diwali sale, read with the
// old-style instanceof + cast chain (pattern matching comes in exercise 2).
class Ex01 {
sealed interface DiscountRule permits FlatDiscount, PercentDiscount, NoDiscountRule {}
record FlatDiscount(long amountPaise) implements DiscountRule {}
record PercentDiscount(double percent) implements DiscountRule {}
record NoDiscountRule() implements DiscountRule {}
static long finalPricePaise(long originalPaise, DiscountRule rule) {
if (rule instanceof FlatDiscount) {
FlatDiscount flat = (FlatDiscount) rule;
return Math.max(0, originalPaise - flat.amountPaise());
} else if (rule instanceof PercentDiscount) {
PercentDiscount percent = (PercentDiscount) rule;
return Math.round(originalPaise * (1 - percent.percent() / 100.0));
} else if (rule instanceof NoDiscountRule) {
return originalPaise;
}
throw new IllegalStateException("unreachable: DiscountRule permits only these three");
}
static String formatted(long paise) {
return "Rs " + (paise / 100) + "." + String.format("%02d", paise % 100);
}
public static void main(String[] args) {
long original = 150000; // Rs 1500.00
DiscountRule[] rules = {
new FlatDiscount(20000),
new PercentDiscount(10.0),
new NoDiscountRule()
};
for (DiscountRule rule : rules) {
System.out.println(rule + " -> " + formatted(finalPricePaise(original, rule)));
}
}
}
solutions/ex02.java
// Exercise 2: a notification sender, refactored from instanceof+cast to
// pattern matching for instanceof (JEP 394), including one guarded pattern.
class Ex02 {
sealed interface Notification permits SmsNotification, EmailNotification, PushNotification {}
record SmsNotification(String phone, String text) implements Notification {}
record EmailNotification(String address, String subject) implements Notification {}
record PushNotification(String deviceToken, String text, int priority) implements Notification {}
static String send(Notification notification) {
if (notification instanceof SmsNotification sms) {
return "SMS to " + sms.phone() + ": " + sms.text();
} else if (notification instanceof EmailNotification email) {
return "Email to " + email.address() + ", subject: " + email.subject();
} else if (notification instanceof PushNotification push) {
return "Push to " + push.deviceToken() + ": " + push.text();
}
throw new IllegalStateException("unreachable");
}
// Guarded pattern: flag a push notification as urgent only when priority is high.
static String urgency(Notification notification) {
if (notification instanceof PushNotification push && push.priority() >= 8) {
return "URGENT push (priority " + push.priority() + ")";
}
if (notification instanceof PushNotification push) {
return "normal push (priority " + push.priority() + ")";
}
return "not a push notification";
}
public static void main(String[] args) {
Notification sms = new SmsNotification("9876543210", "Your OTP is 4821");
Notification email = new EmailNotification("[email protected]", "Order shipped");
Notification lowPush = new PushNotification("device-101", "Weekly summary ready", 3);
Notification highPush = new PushNotification("device-102", "Payment failed, action needed", 9);
for (Notification n : new Notification[] {sms, email, lowPush, highPush}) {
System.out.println(send(n));
}
System.out.println();
for (Notification n : new Notification[] {sms, lowPush, highPush}) {
System.out.println(urgency(n));
}
}
}
solutions/ex03.java
// Exercise 3: a loan-application decision switch with guards (`when`), exhaustive
// over a sealed LoanDecision -- no default needed.
import java.util.List;
class Ex03 {
sealed interface LoanDecision permits Approved, Rejected, PendingReview {}
record Approved(String applicant, long amountPaise, double interestRatePercent) implements LoanDecision {}
record Rejected(String applicant, String reason) implements LoanDecision {}
record PendingReview(String applicant, String missingDocument) implements LoanDecision {}
static String message(LoanDecision decision) {
return switch (decision) {
case Approved a when a.amountPaise() >= 10_00_000_00L ->
a.applicant() + ": approved for a large amount, needs branch manager sign-off before disbursal";
case Approved a ->
a.applicant() + ": approved, Rs " + (a.amountPaise() / 100) + " at " + a.interestRatePercent() + "% interest";
case Rejected r -> r.applicant() + ": rejected (" + r.reason() + ")";
case PendingReview p -> p.applicant() + ": pending, missing " + p.missingDocument();
};
}
public static void main(String[] args) {
List<LoanDecision> decisions = List.of(
new Approved("Ravi Shah", 50_00_00L, 9.5),
new Approved("Meera Iyer", 15_00_000_00L, 8.75),
new Rejected("Arjun Nair", "credit score below threshold"),
new PendingReview("Asha Kulkarni", "income proof"));
decisions.forEach(d -> System.out.println(message(d)));
}
}
solutions/ex04.java
// Exercise 4: a Tatkal booking's seat-allocation field can be null (not yet
// allocated), a String (a confirmed seat number), or an Integer (waitlist
// position) -- classified with a switch that handles `case null` explicitly.
class Ex04 {
static String seatStatus(Object allocation) {
return switch (allocation) {
case null -> "not yet allocated, check again closer to departure";
case Integer position when position <= 5 -> "waitlisted at #" + position + ", likely to confirm";
case Integer position -> "waitlisted at #" + position + ", unlikely to confirm";
case String seat when seat.startsWith("RAC") -> "RAC seat, shared berth: " + seat;
case String seat -> "confirmed seat: " + seat;
default -> "unrecognized allocation value: " + allocation;
};
}
public static void main(String[] args) {
Object[] allocations = {null, 3, 42, "RAC-12", "B4-22", 7.5};
for (Object allocation : allocations) {
System.out.println(seatStatus(allocation));
}
}
}
solutions/ex05.java
// Exercise 5: nested record pattern deconstruction for an order's shipping
// summary, three levels deep (Order -> Customer/Address -> Pincode), with a
// guard that flags high-value Maharashtra orders for priority dispatch.
import java.util.List;
class Ex05 {
record Pincode(String code, String state) {}
record Address(String line1, String city, Pincode pincode) {}
record Customer(String name, String phone) {}
record Order(String id, Customer customer, Address address, long totalPaise) {}
static String shippingSummary(Object maybeOrder) {
if (maybeOrder instanceof Order(
String id,
Customer(String name, var phone),
Address(var line1, String city, Pincode(var code, String state)),
long totalPaise) && state.equals("Maharashtra") && totalPaise >= 5_00_000L) {
return id + ": PRIORITY DISPATCH -- " + name + ", " + city + " - " + code + " (" + state + "), Rs " + (totalPaise / 100);
}
if (maybeOrder instanceof Order(String id, Customer(String name, var phone), Address(var line1, String city, Pincode(var code, var state)), long totalPaise)) {
return id + ": " + name + ", " + city + " - " + code + " (" + state + "), Rs " + (totalPaise / 100);
}
return "not an order";
}
public static void main(String[] args) {
List<Order> orders = List.of(
new Order("ORD-9001",
new Customer("Asha Kulkarni", "9876543210"),
new Address("12 FC Road", "Pune", new Pincode("411005", "Maharashtra")),
6_50_000L),
new Order("ORD-9002",
new Customer("Ravi Shah", "9123456780"),
new Address("4 Gandhi Nagar", "Ahmedabad", new Pincode("380001", "Gujarat")),
6_50_000L),
new Order("ORD-9003",
new Customer("Meera Iyer", "9988776655"),
new Address("9 MG Road", "Mumbai", new Pincode("400001", "Maharashtra")),
1_20_000L));
for (Order order : orders) {
System.out.println(shippingSummary(order));
}
System.out.println(shippingSummary("not even an order"));
}
}
solutions/ex06.java
// Exercise 6: exhaustiveness as a safety net. Vehicle originally permitted only
// Bike and Car; adding Bus to `permits` without updating tollFeePaise's switch
// fails to compile (see exercises.md for the real captured error) -- this file
// is the FIXED version, with Bus handled.
class Ex06 {
sealed interface Vehicle permits Bike, Car, Bus {}
record Bike(String reg) implements Vehicle {}
record Car(String reg) implements Vehicle {}
record Bus(String reg, int seatingCapacity) implements Vehicle {}
static long tollFeePaise(Vehicle vehicle) {
return switch (vehicle) {
case Bike b -> 0L;
case Car c -> 6_500L;
case Bus b when b.seatingCapacity() > 40 -> 22_000L;
case Bus b -> 15_000L;
};
}
public static void main(String[] args) {
Vehicle[] vehicles = {
new Bike("MH12AB1234"),
new Car("MH12CD5678"),
new Bus("MH12EF9012", 50),
new Bus("MH12GH3456", 30)
};
for (Vehicle vehicle : vehicles) {
System.out.println(vehicle + " -> toll Rs " + (tollFeePaise(vehicle) / 100));
}
}
}
solutions/ex07.java
// Exercise 7: a second webhook-style router, for e-commerce order events,
// built the same way as the part's own WebhookEventRouter.
import java.util.List;
class Ex07 {
sealed interface OrderEvent permits OrderPlaced, OrderShipped, OrderCancelled, PaymentRefunded {}
record OrderPlaced(String orderId, long totalPaise) implements OrderEvent {}
record OrderShipped(String orderId, String courier, String trackingId) implements OrderEvent {}
record OrderCancelled(String orderId, String reason) implements OrderEvent {}
record PaymentRefunded(String orderId, long amountPaise) implements OrderEvent {}
static String route(OrderEvent event) {
return switch (event) {
case OrderPlaced(var orderId, var totalPaise) when totalPaise >= 50_000_00L ->
"WAREHOUSE " + orderId + ": high-value order (Rs " + (totalPaise / 100) + "), verify stock before packing";
case OrderPlaced(var orderId, var totalPaise) ->
"WAREHOUSE " + orderId + ": pack order, Rs " + (totalPaise / 100);
case OrderShipped(var orderId, var courier, var trackingId) ->
"NOTIFY " + orderId + ": shipped via " + courier + ", tracking " + trackingId;
case OrderCancelled(var orderId, var reason) when reason.equals("OUT_OF_STOCK") ->
"WAREHOUSE " + orderId + ": cancelled (out of stock), trigger restock alert";
case OrderCancelled(var orderId, var reason) ->
"SUPPORT " + orderId + ": cancelled (" + reason + ")";
case PaymentRefunded(var orderId, var amountPaise) ->
"LEDGER " + orderId + ": refunded Rs " + (amountPaise / 100);
};
}
public static void main(String[] args) {
List<OrderEvent> events = List.of(
new OrderPlaced("ORD-8001", 149900),
new OrderPlaced("ORD-8002", 7500000),
new OrderShipped("ORD-8001", "BlueDart", "BD1234567890"),
new OrderCancelled("ORD-8003", "OUT_OF_STOCK"),
new OrderCancelled("ORD-8004", "CUSTOMER_REQUEST"),
new PaymentRefunded("ORD-8003", 299900));
events.forEach(e -> System.out.println(route(e)));
}
}
solutions/ex08.java
// Exercise 8 (stretch): a two-level sealed hierarchy -- Vehicle permits
// TwoWheeler and FourWheeler, each of those sealed again over the actual
// vehicle types -- with one switch over the leaf types, still exhaustive.
import java.util.List;
class Ex08 {
sealed interface Vehicle permits TwoWheeler, FourWheeler {}
sealed interface TwoWheeler extends Vehicle permits Bike, Scooter {}
sealed interface FourWheeler extends Vehicle permits Car, Van {}
record Bike(String reg) implements TwoWheeler {}
record Scooter(String reg) implements TwoWheeler {}
record Car(String reg, int seats) implements FourWheeler {}
record Van(String reg, double cargoCubicMeters) implements FourWheeler {}
// The compiler can see Vehicle = TwoWheeler|FourWheeler, TwoWheeler =
// Bike|Scooter, FourWheeler = Car|Van -- so a switch over just the four
// leaf types is already exhaustive for Vehicle. No default needed, even
// though the leaf types sit two levels below Vehicle itself.
static String parkingSlot(Vehicle vehicle) {
return switch (vehicle) {
case Bike b -> "two-wheeler slot (bike): " + b.reg();
case Scooter s -> "two-wheeler slot (scooter): " + s.reg();
case Car c when c.seats() > 5 -> "large four-wheeler slot: " + c.reg();
case Car c -> "standard four-wheeler slot: " + c.reg();
case Van v -> "loading-bay slot: " + v.reg() + " (" + v.cargoCubicMeters() + " m3)";
};
}
public static void main(String[] args) {
List<Vehicle> vehicles = List.of(
new Bike("MH12AB1234"),
new Scooter("MH12CD5678"),
new Car("MH12EF9012", 5),
new Car("MH12GH3456", 7),
new Van("MH12IJ7890", 4.5));
vehicles.forEach(v -> System.out.println(parkingSlot(v)));
}
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Forgetting final/sealed/non-sealed on a permitted subtype |
Doesn't compile — every direct subtype of a sealed type must pick one | Add the modifier that matches intent; final unless you deliberately want more subclasses |
Assuming an if/else instanceof chain is exhaustive |
The compiler never checks it; a missed case falls through silently (or into a thrown exception, if you remembered to add one) | switch over a sealed type instead — the compiler checks exhaustiveness for you |
| Reusing a pattern variable's name for an unrelated existing local | Compile error, not a silent shadowing bug | Pick a different name — the compiler catches the clash immediately |
A switch over Object (or any non-sealed type) with no default |
Doesn't compile — the compiler cannot prove every possible subtype is covered | Add default, or switch over a sealed type / enum if you want true exhaustiveness |
Treating case null as optional "just in case" |
A switch on a possibly-null subject with no case null still throws NullPointerException, same as before Java 21 |
Add case null -> explicitly whenever the subject might be null |
| Putting the unconditional case before the guarded one for the same type | The unconditional case matches first and the guard never gets evaluated | Order the guarded (when) case before its unconditional fallback, same as any switch's top-to-bottom rule |
| Deconstructing a record pattern field you never use | Works, but adds noise | Use var or omit matching further and just bind the whole record with a type pattern instead |
Quick recap
sealed ... permitscloses a hierarchy to a named list of types; every direct subtype must befinal,sealed, ornon-sealed.- Pattern matching for
instanceof(JEP 394, Java 16) tests and binds in one step, including guarded patterns with&&. - Pattern matching for
switch(JEP 441, Java 21) adds type patterns,whenguards, and an explicitcase null; aswitchover asealedtype needs nodefaultonce every permitted case is handled. - Record patterns (JEP 440, Java 21) deconstruct a record's components in
instanceoforswitch, nested as deep as the records go. - Records (Java 16+) still generate the constructor, accessors,
equals/hashCode/toString; a compact constructor validates, a static factory reads better than a rawnewat some call sites. - Java 17 (LTS) finalized
sealed; Java 21 (LTS) finalized pattern-matchingswitch, record patterns, virtual threads and sequenced collections — one idea landing across five releases. - A sealed interface of records, routed through an exhaustive, deconstructing
switch, is the idiomatic Java 21 way to model and handle a closed set of event types.
Checklist
- I can explain what
permitsdoes and why every direct subtype needsfinal,sealed, ornon-sealed. - I replaced an
instanceof+ cast pair with a single pattern-matchinginstanceof, including a guarded pattern. - I wrote an exhaustive
switchover a sealed interface with nodefault, and awhenguard that runs before its unconditional fallback. - I wrote a
switchwith an explicitcase null. - I deconstructed a nested record with a record pattern, two levels deep or more.
- I can name which of sealed types, pattern-matching switch, record patterns, and virtual threads finalized in Java 17 versus Java 21.
- I built the webhook router end to end: a sealed event hierarchy, a guarded exhaustive switch, and a
case null/defaultlayer for raw payloads.