Java 21: Evaluate and simplify an expression tree. Compare instanceof chains, polymorphism, the visitor and pattern matching for switch with record patterns.
Problem
Model arithmetic expressions Num, Add, Mul, Neg and implement eval and simplify (x + 0 → x, x * 1 → x, x * 0 → 0, --x → x). It is the textbook showcase for Java 21's pattern matching for switch (JEP 441) and record patterns (JEP 440).
sealed interface Expr permits Num, Add, Mul, Neg {}
record Num(int value) implements Expr {}
record Add(Expr left, Expr right) implements Expr {}
record Mul(Expr left, Expr right) implements Expr {}
record Neg(Expr inner) implements Expr {}Approach 1: instanceof chain with casts (Java 8 style)
Repetitive casts, no exhaustiveness check, and nested conditions get unreadable for simplify.
class EvalInstanceof {
static int eval(Expr e) {
if (e instanceof Num) return ((Num) e).value();
if (e instanceof Add) { Add a = (Add) e; return eval(a.left()) + eval(a.right()); }
if (e instanceof Mul) { Mul m = (Mul) e; return eval(m.left()) * eval(m.right()); }
if (e instanceof Neg) return -eval(((Neg) e).inner());
throw new IllegalArgumentException("unknown " + e);
}
}Approach 2: Polymorphism (an eval() method on each type)
Clean for one operation, but simplify, print, derive and so on would all have to be added to every class, and simplification rules span several types (they look at children).
interface PolyExpr { int eval(); }
record PNum(int value) implements PolyExpr { public int eval() { return value; } }
record PAdd(PolyExpr l, PolyExpr r) implements PolyExpr { public int eval() { return l.eval() + r.eval(); } }
record PMul(PolyExpr l, PolyExpr r) implements PolyExpr { public int eval() { return l.eval() * r.eval(); } }Approach 3: Visitor pattern
Type-safe and keeps operations separate, but needs accept boilerplate in every type and a class per operation; nested matches (looking at a child's type) still need extra instanceof checks.
Approach 4: Pattern matching for switch + record patterns (Java 21)
case Add(Expr l, Expr r)deconstructs the record and binds its components.- Patterns nest:
case Add(Num(int v), Expr r) when v == 0matches "0 + r" in one line. whenadds a guard.- Over a sealed type, the compiler checks the switch is exhaustive, so adding a new
Exprsubtype breaks compilation until every switch handles it: no default branch hiding bugs.
class ExprOps {
static int eval(Expr e) {
return switch (e) {
case Num n -> n.value();
case Add(Expr l, Expr r) -> eval(l) + eval(r);
case Mul(Expr l, Expr r) -> eval(l) * eval(r);
case Neg(Expr inner) -> -eval(inner);
};
}
static Expr simplify(Expr e) {
return switch (e) {
case Add(Expr l, Expr r) -> simplifyAdd(simplify(l), simplify(r));
case Mul(Expr l, Expr r) -> simplifyMul(simplify(l), simplify(r));
case Neg(Neg(Expr inner)) -> simplify(inner); // --x → x
case Neg(Num(int v)) -> new Num(-v);
case Neg(Expr inner) -> new Neg(simplify(inner));
case Num n -> n;
};
}
private static Expr simplifyAdd(Expr l, Expr r) {
return switch (new Add(l, r)) {
case Add(Num(int a), Num(int b)) -> new Num(a + b); // constant folding
case Add(Num(int z), Expr x) when z == 0 -> x; // 0 + x
case Add(Expr x, Num(int z)) when z == 0 -> x; // x + 0
case Add a -> a;
};
}
private static Expr simplifyMul(Expr l, Expr r) {
return switch (new Mul(l, r)) {
case Mul(Num(int a), Num(int b)) -> new Num(a * b);
case Mul(Num(int z), Expr x) when z == 0 -> new Num(0);
case Mul(Expr x, Num(int z)) when z == 0 -> new Num(0);
case Mul(Num(int one), Expr x) when one == 1 -> x;
case Mul(Expr x, Num(int one)) when one == 1 -> x;
case Mul m -> m;
};
}
static String show(Expr e) {
return switch (e) {
case Num(int v) when v < 0 -> "(" + v + ")";
case Num(int v) -> String.valueOf(v);
case Add(var l, var r) -> "(" + show(l) + " + " + show(r) + ")"; // var in record patterns
case Mul(var l, var r) -> show(l) + " * " + show(r);
case Neg(var inner) -> "-" + show(inner);
};
}
}
class ExprDemo {
public static void main(String[] args) {
Expr x = new Add(new Mul(new Num(1), new Add(new Num(3), new Num(0))), new Neg(new Neg(new Num(4))));
System.out.println(ExprOps.show(x) + " = " + ExprOps.eval(x) + " = " + EvalInstanceof.eval(x)); // ... = 7 = 7
System.out.println(ExprOps.show(ExprOps.simplify(x))); // 7
System.out.println(new PAdd(new PNum(2), new PMul(new PNum(3), new PNum(4))).eval()); // 14
System.out.println(ExprOps.show(ExprOps.simplify(new Mul(new Add(new Num(0), new Num(5)), new Neg(new Num(2)))))); // (-10)
}
}Feasible → optimal
All approaches are O(size of the tree). The instanceof chain is feasible but fragile; polymorphism suits single, type-local operations; the visitor is safe but heavy. Pattern matching for switch over sealed records is the optimal Java 21 answer for tree-shaped data with many operations: concise, nested matching, guards, and compiler-checked exhaustiveness.
Follow-up questions interviewers ask
Try answering each one before you open it.
In what order are case labels checked, and what is dominance?
Cases are tested top to bottom and the first match wins. The compiler rejects a case that can never match because an earlier one dominates it: case Add a before case Add(Num n, Expr r) is an error. Guarded cases (when) must come before the unguarded case for the same pattern. Constant labels must precede type patterns of the same type.
How does a pattern switch handle null?
Traditionally switch on null throws NullPointerException, and pattern switches keep that behaviour unless you add case null -> (or case null, default ->). This keeps old code's semantics while letting new code handle null explicitly in one place.