Skip to lesson
MentorNxt home

Java Programming

Pattern Matching & Newer Language Features

Modern Java features: practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Most bugs with modern Java features come from a few habits carried over from older code: a default that hides a new type, a loose guard placed before a strict one, a var that picked the wrong type, and a text block whose closing quotes sit in the wrong place. Each is easy to fix once you know what to look for.

Mistake 1: an if-else type chain where an exhaustive switch fits

Code written before Java 21 often checks types in a long chain: if (p instanceof Upi u) ... else if (p instanceof Card c) ... else throw .... It works, but the compiler cannot tell you when a branch is missing.

  1. Make the parent type sealed, listing every subtype in permits.
  2. Turn each instanceof branch into case Type t ->.
  3. Turn each extra condition into a when guard, strictest first.
  4. End every type with an unguarded case and drop the final else or default.

Example 1 · From an if-else type chain to an exhaustive switch

FeeSwitchDemo.javaJava
// Java 21import java.util.List;
sealed interface Fee permits Tuition, Hostel, Transport { }
record Tuition(int amount, boolean scholarship) implements Fee { }
record Hostel(int months, int perMonth) implements Fee { }
record Transport(int km) implements Fee { }
public class FeeSwitchDemo {    // before: the compiler cannot see a missing branch    static int payableOld(Fee f) {        if (f instanceof Tuition t && t.scholarship()) {            return t.amount() / 2;        } else if (f instanceof Tuition t) {            return t.amount();        } else if (f instanceof Hostel h) {            return h.months() * h.perMonth();        } else if (f instanceof Transport tr && tr.km() > 15) {            return 12000;        } else if (f instanceof Transport tr) {            return 8000;        }        throw new IllegalArgumentException("Unknown fee");    }
    // after: one case per rule, checked by the compiler    static int payable(Fee f) {        return switch (f) {            case Tuition t when t.scholarship() -> t.amount() / 2;            case Tuition t -> t.amount();            case Hostel h -> h.months() * h.perMonth();            case Transport tr when tr.km() > 15 -> 12000;            case Transport tr -> 8000;        };    }
    public static void main(String[] args) {        List<Fee> fees = List.of(new Tuition(90000, true), new Hostel(10, 6500), new Transport(22), new Transport(9));        int total = 0;        for (Fee f : fees) {            System.out.println(f + " -> Rs " + payable(f) + " (old way Rs " + payableOld(f) + ")");            total += payable(f);        }        System.out.println("Total payable: Rs " + total);    }}
Output
Tuition[amount=90000, scholarship=true] -> Rs 45000 (old way Rs 45000)
Hostel[months=10, perMonth=6500] -> Rs 65000 (old way Rs 65000)
Transport[km=22] -> Rs 12000 (old way Rs 12000)
Transport[km=9] -> Rs 8000 (old way Rs 8000)
Total payable: Rs 130000

What this code does

  • Each if branch became one case, and each extra condition became a when guard placed above the unguarded case of the same type. Both methods give the same amounts.
  • Fee is sealed and every subtype ends with an unguarded case, so the switch needs no default. Adding a LabFee record to permits would now break the build at this switch, instead of throwing at run time.

A new payment type simply falls to the final else at run time.

If the types form a closed family, make the parent a sealed interface and rewrite the chain as a switch with one case per subtype and no default (Java 21). Each condition inside a branch becomes a when guard. Now a missing or newly added type is a compile error.

Mistake 2: case order, dominance and guards

Two different order bugs look similar. A broad type above a narrow one, or an unguarded case above a guarded case of the same type, is a compile error: "this case label is dominated by a preceding case label". Move the specific case up.

Example 2 · One parser, four features: instanceof, type patterns, guards, case null

InputParserDemo.javaJava
// Java 21import java.util.Arrays;import java.util.List;
record Range(int from, int to) { }
public class InputParserDemo {    static String read(Object input) {        return switch (input) {            case null -> "no input";            case String s when s.isBlank() -> "blank text";            case String s when s.strip().chars().allMatch(Character::isDigit) -> "number " + Integer.parseInt(s.strip());            case String s -> "word " + s.strip();            case Integer n when n < 0 -> "negative " + n;            case Integer n -> "number " + n;            case Range(int a, int b) when a > b -> "empty range";            case Range(int a, int b) -> "range of " + (b - a + 1);            default -> "unsupported " + input.getClass().getSimpleName();        };    }
    public static void main(String[] args) {        List<Object> inputs = Arrays.asList(" 42 ", "  ", "Pune", -5, 7, new Range(3, 9), new Range(9, 3), null, 2.5);        for (Object in : inputs) {            System.out.println(read(in));        }
        Object first = inputs.get(0);        if (first instanceof String s && !s.isBlank()) {            System.out.println("First input stripped: [" + s.strip() + "]");        }    }}
Output
number 42
blank text
word Pune
negative -5
number 7
range of 7
empty range
no input
unsupported Double
First input stripped: [42]

What this code does

  • Every guarded case sits above the unguarded case of its type, and the strict number check on text comes before the general word case. case null handles the missing value inside the switch.
  • The record pattern Range(int a, int b) with a guard rejects reversed ranges. The final instanceof check shows the Java 16 pattern with &&, which works on Java 17 too.

The second bug compiles: a loose guard above a strict guard of the same type, like when m >= 35 above when m >= 90. The compiler cannot compare guard conditions, so the strict case is silently never reached. Order range guards from strictest to loosest, and test the boundary values. The same care applies to instanceof: a pattern variable can be used after && but not after ||, and after a negated check only on the lines that follow it.

Mistake 3: var that picked the wrong type

var copies the exact type of the starting value. var rate = 18; is an int, so price * rate / 100 drops the paise. var items = new ArrayList<>(); is an ArrayList<Object>, so its elements lose their methods.

VarTypes.javaJava
import java.util.*;
public class VarTypes {    public static void main(String[] args) {        int price = 999;        var rate = 18;        System.out.println(price * rate / 100);        var exactRate = 18.0;        System.out.println(price * exactRate / 100);        var items = new ArrayList<String>();        items.add("pen");        System.out.println(items.get(0).toUpperCase());    }}
Output
179
179.82
PEN

var result = engine.run(); compiles, but no reader knows what result is.

The fixes are small: write a double literal (18.0) or the type itself, put the element type in the diamond (new ArrayList<String>()), and write the real type when the right side hides it.

Mistake 4: text block indentation and nested record nulls

In a text block, the closing """ counts when Java measures the common indentation. If it sits to the left of the text, every line keeps extra spaces at the start.

Example 3 · Mistakes: var picked int, and a text block indented too far

VarTextBlockBugsDemo.javaJava
import java.util.ArrayList;
public class VarTextBlockBugsDemo {    public static void main(String[] args) {        // bug: var made rate an int, so the GST loses its paise        var price = 249;        var rate = 18;        System.out.println("Wrong GST: " + (price * rate / 100));        var rateFixed = 18.0;        System.out.println("Right GST: " + (price * rateFixed / 100));
        // bug: the empty diamond made an ArrayList<Object>        var labs = new ArrayList<String>();        labs.add("OS lab");        System.out.println("First lab in capitals: " + labs.get(0).toUpperCase());
        // bug: closing quotes 4 spaces left of the text        String wrong = """                Room 101                Room 102            """;        String right = """                Room 101                Room 102                """;        wrong.lines().forEach(l -> System.out.println("wrong [" + l + "]"));        right.lines().forEach(l -> System.out.println("right [" + l + "]"));    }}
Output
Wrong GST: 44
Right GST: 44.82
First lab in capitals: OS LAB
wrong [    Room 101]
wrong [    Room 102]
right [Room 101]
right [Room 102]

What this code does

  • var rate = 18 is an int, so 249 * 18 / 100 is integer division and gives 44 instead of 44.82. A double literal fixes it. With the element type in the diamond, labs.get(0) is a String again.
  • In wrong, the closing """ sets the common indentation, so 4 extra spaces stay at the start of each line. Lining it up with the text removes them.

Example 4 · Billing calculator with nested record patterns

BillingDemo.javaJava
// Java 21import java.util.List;
record Item(String name, int price, String category) { }
sealed interface Line permits Product, Service, Discount { }
record Product(Item item, int qty) implements Line { }
record Service(String name, int hours, int ratePerHour) implements Line { }
record Discount(String code, int percent) implements Line { }
public class BillingDemo {    static int gstPercent(String category) {        return switch (category) {            case "books" -> 0;            case "groceries" -> 5;            default -> 18;        };    }
    static int lineTotal(Line line) {        return switch (line) {            case Product(Item(var name, var price, var cat), var qty) -> {                int base = price * qty;                yield base + base * gstPercent(cat) / 100;            }            case Service(var name, var hours, var rate) -> {                int base = hours * rate;                yield base + base * 18 / 100;            }            case Discount d -> 0;        };    }
    public static void main(String[] args) {        List<Line> bill = List.of(                new Product(new Item("Java book", 450, "books"), 2),                new Product(new Item("Headphones", 1500, "electronics"), 1),                new Service("Laptop repair", 2, 400),                new Discount("FEST10", 10));
        int subtotal = 0;        int percentOff = 0;        for (Line line : bill) {            if (line instanceof Discount(var code, var percent)) {                percentOff = percent;                System.out.println("Coupon " + code + ": " + percent + "% off");            } else {                System.out.println(line + " -> Rs " + lineTotal(line));                subtotal += lineTotal(line);            }        }        int total = subtotal - subtotal * percentOff / 100;        System.out.println("Subtotal Rs " + subtotal + ", total Rs " + total);    }}
Output
Product[item=Item[name=Java book, price=450, category=books], qty=2] -> Rs 900
Product[item=Item[name=Headphones, price=1500, category=electronics], qty=1] -> Rs 1770
Service[name=Laptop repair, hours=2, ratePerHour=400] -> Rs 944
Coupon FEST10: 10% off
Subtotal Rs 3614, total Rs 3253

What this code does

  • Product(Item(var name, var price, var cat), var qty) reaches into the nested Item in one pattern, so the case body uses price, qty and cat directly. GST is 0% on books, 5% on groceries and 18% on everything else here.
  • The coupon is read with a record pattern after instanceof. Line is sealed, so lineTotal covers all three line types without a default.

Line it up with the text, or put it at the end of the last line when you do not want a final line break. Spaces at the end of lines are stripped, so padding needs \s or %-10s.

Nested record patterns have their own trap: Order(var id, Address(var city, var pin)) never matches an order whose address is null. In a billing or delivery switch, add a case with a plain type pattern, such as Order(var id, var to), to handle the missing part on purpose.

When a modern feature behaves oddly, first check the Java version: switch patterns, guards, record patterns and sequenced collections need Java 21.

Finish up

Mark complete & continue

Next: Refactor a marks report to streams