Quiz: Java Pattern Matching for switch: Type Patterns, Record Patterns and when
Study the lesson first: 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?
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, notnull; - 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,defaultand the combinedcase 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?
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
Objectwithoutdefaultjavac reportsthe switch statement does not cover all possible input values. Fixes: adefault, an unconditional patterncase Object oas the last branch, or a sealed type with all its variants.case Object oanddefaulttogether are an error:switch has both an unconditional pattern and a default label. - Primitive selector.
switch (x)on anintwithcase Integer idoes 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?
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 variablesis guaranteed to be a non-nullString. - Guarded branches go above the unconditional branch of the same type, otherwise you get a dominance error.
whencan follow only a pattern:case 1 when x > 0givesguards 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, andcase Integer i when falseis a compile error. whenis a contextual keyword: a variable namedwhenis 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?
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, thencase String s- error; the other way round - compiles.case Integer i, thencase Integer i when i > 0- error; the guarded branch above the unconditional one - compiles.case Integer i, thencase 42- error; the constant above the pattern - compiles.default, thencase String s- error: patterns afterdefaultare not allowed. Constants afterdefault(a switch onint) are still legal.case Object oanddefaultin 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?
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, includingnull.
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?
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 -> ...
varin 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 sfor aStringcomponent) matches anullcomponent too. A narrowing pattern (Box<?>(String s)) rejectsnull. - The compiler checks exhaustiveness over combinations of sealed components:
Pair(Round, Round),Pair(Round, Quad),Pair(Quad, Figure)cover every pair withoutdefault. - If a component is
nulland no branch matches, an exhaustive switch throwsMatchException, notNullPointerException.
7. When should you use pattern matching in a switch, and when polymorphism (virtual methods)?
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.