Quiz: Java Pattern Matching for switch: Type Patterns, Record Patterns and when

Total: 7 questions

1. 

What is pattern matching for switch in Java, and which labels can a modern switch use?

Pattern matching for switch is a Java feature in which a case label tests not a value but the type or record structure of an object and declares a variable of the right type at the same time. One switch with labels case Integer i ->, case String s -> replaces a chain of if (o instanceof Integer i) ... else if .... It is standard since Java 21: JEP 441 (pattern matching for switch) and JEP 440 (record patterns); in Java 17-20 it was a preview feature.

Label kinds:

  • constant - case 1, 2, case "yes", case RED;
  • type pattern - case String s: an object of that type, not null;
  • record pattern - case Point(int x, int y): a record whose components match the nested patterns;
  • guarded pattern - case Integer i when i > 0;
  • case null, default and the combined case null, default.

Compared with an if chain, the compiler also checks the order of branches (dominance) and that no case is forgotten (exhaustiveness).

2. 

How does a switch on type (type patterns) work: what can the selector be, where is the pattern variable visible, and is default required?

A type pattern case Type name matches if the selector is not null and is an instance of the type. The selector can be of any reference type: Object, an interface, an abstract class, an array (case int[] arr).

  • Scope. A pattern variable is visible only in its own branch; in another branch or after the switch you get cannot find symbol.
  • Generics. A type argument cannot be checked because of erasure, so you write case List<?> list.
  • Exhaustiveness. A switch with patterns - expression or statement - must cover every value. For Object without default javac reports the switch statement does not cover all possible input values. Fixes: a default, an unconditional pattern case Object o as the last branch, or a sealed type with all its variants. case Object o and default together are an error: switch has both an unconditional pattern and a default label.
  • Primitive selector. switch (x) on an int with case Integer i does not compile without --enable-preview: primitive patterns are a preview feature and are disabled by default.
3. 

What is a guarded pattern (the when clause) in a switch, and what rules apply to it?

A guarded pattern is a label case Type name when condition ->. The branch runs only if the pattern matches and the condition returns true; otherwise matching continues with the next labels.

  • The condition is evaluated only after the type matches, so in case String s when s.isBlank() the variable s is guaranteed to be a non-null String.
  • Guarded branches go above the unconditional branch of the same type, otherwise you get a dominance error.
  • when can follow only a pattern: case 1 when x > 0 gives guards are only allowed for case with a pattern.
  • Outer local variables used in the condition must be final or effectively final: local variables referenced from a guard must be final or effectively final.
  • The compiler does not analyse the contents of when: guarded branches do not count toward exhaustiveness, and case Integer i when false is a compile error.
  • when is a contextual keyword: a variable named when is still legal.
  • The condition should have no side effects (logging, counters): it can run for an object that ends up in another branch.

In the Java 17-18 previews the condition was written with &&; Java 19 (JEP 427) replaced it with when.

4. 

What is label dominance in a switch, and in what order should branches be written?

Dominance is the rule that a label cannot come after another label that matches all of its values. Such a branch can never run, and javac reports this case label is dominated by a preceding case label. The general principle is from specific to general.

  • case CharSequence cs, then case String s - error; the other way round - compiles.
  • case Integer i, then case Integer i when i > 0 - error; the guarded branch above the unconditional one - compiles.
  • case Integer i, then case 42 - error; the constant above the pattern - compiles.
  • default, then case String s - error: patterns after default are not allowed. Constants after default (a switch on int) are still legal.
  • case Object o and default in one switch - switch has both an unconditional pattern and a default label.

The compiler compares only types and does not look into when: case 42 after case Integer i when i > 0 compiles but never matches. That is why constants go above the patterns of their type.

5. 

How does a switch with patterns handle null, and what do case null and case null, default do?

If the selector is null and the switch has no case null label, it throws NullPointerException before any label is checked. This applies to a switch with patterns too: neither default nor the unconditional case Object o catches null - a top-level pattern matches only objects. The old switch behaviour is kept for compatibility.

null can be handled only explicitly:

  • case null -> ... - a separate branch;
  • case null, default -> ... - everything else, including null.

Restrictions: case null can be combined with a comma only with default - case null, String s gives invalid case label combination. A switch statement with case null becomes a “new” switch and must be exhaustive even on a plain String.

6. 

How do nested and generic record patterns work in a switch, and how do they behave with null components?

A record pattern case Point(int x, int y) checks that the object is that record and splits it into components. A component position can hold another pattern, so an object of any depth is taken apart by one label:

case Line(Point(var x1, var y1), Point p2) when x1 > 0 -> ...
  • var in a component means the component type as declared in the record.
  • For a generic record the type argument can be omitted: with a Box<String> selector, case Box(String s) infers it.
  • A record pattern itself never matches null. But a nested pattern that is unconditional for the component type (var v, String s for a String component) matches a null component too. A narrowing pattern (Box<?>(String s)) rejects null.
  • The compiler checks exhaustiveness over combinations of sealed components: Pair(Round, Round), Pair(Round, Quad), Pair(Quad, Figure) cover every pair without default.
  • If a component is null and no branch matches, an exhaustive switch throws MatchException, not NullPointerException.
7. 

When should you use pattern matching in a switch, and when polymorphism (virtual methods)?

They solve opposite problems (the expression problem):

  • Polymorphism fits when new types are added often and the set of operations is stable. The logic lives in each class next to its data; a new type is one new class. A new operation needs a method in the interface and in every class. Typical uses: plugins, strategies, hierarchies open for extension.
  • A switch over a sealed hierarchy fits when the set of types is fixed and operations are added all the time and should not live inside the classes. A new operation is one method with a switch; when a new type appears, the compiler points to every switch that needs a new branch. It also works with types from someone else's library. Typical uses: ASTs and interpreters, events, API responses, a success/failure Result.

The style “records for data + a sealed interface + switch for behaviour” is called data-oriented programming.

Page 1 of 1