Quick revision
The short answer
We write return switch (obj) { case null -> "null"; case String s when s.length() > 10 -> "long " + s.length(); case String s -> "short string"; case Integer i -> "int"; default -> "other"; };. The when clause adds a guard to a pattern, case null handles null explicitly (without it the switch throws NullPointerException), and the guarded String case must come before the plain String case, because a more general pattern before a more specific one is a dominance compile error. Pattern matching for switch is final since Java 21 (JEP 441).
What to remember
In this answer, we replaced an if-instanceof chain with a pattern switch: case null returns "null", a guarded case String s when s.length() > 10 returns the length, a plain String case returns "short string", Integer returns "int" and default returns "other". We saw that when adds a guard, that without case null the switch throws NullPointerException, that default does not cover null, and that a general pattern before a specific one is a dominance compile error. The feature is final since Java 21 through JEP 441.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We write return switch (obj) { case null -> "null"; case String s when s.length() > 10 -> "long " + s.length(); case String s -> "short string"; case Integer i -> "int"; default -> "other"; };. The when clause adds a guard to a pattern, case null handles null explicitly (without it the switch throws NullPointerException), and the guarded String case must come before the plain String case, because a more general pattern before a more specific one is a dominance compile error. Pattern matching for switch is final since Java 21 (JEP 441).
Why this question is asked
For most of Java's history, a switch could only test a value against constants, so classifying an Object by its type meant a chain of if statements with instanceof and casts. Pattern matching for switch replaces that chain with one expression that the compiler checks for order and completeness. Interviewers use this small exercise because it touches every rule of the feature at once: type patterns, guards, null handling, ordering and default. In this answer, we will see the old if-chain, write the switch, walk through each case with results, and look at the null and dominance rules in detail.
1The Old Way: An if-else Chain
Before Java 21, the natural code tests each type in turn. It works, but the null check has to come first or a later method call could fail, the order of checks is easy to get wrong, and nothing tells us if a branch can never be reached.
2The Switch With Patterns
With pattern matching for switch, each case can be a type pattern, optionally followed by a guard, and the switch is an expression that returns a value.
- case null?YesReturn "null"NoNext case
- String and length > 10?YesReturn "long " + lengthNoNext case
- String?YesReturn "short string"NoNext case
- Integer?YesReturn "int"NoNext case
- defaultReturn "other"
5 steps in order. Play them, or step through them one at a time.
Cases are tried in order; "switch" has 6 characters, so the third case wins.
The cases are tried from top to bottom, and the first one that matches wins. A case like case String s matches any String and binds it to s, which is in scope only in that case. The arrow form never falls through to the next case, so there is no break to forget. Because obj is an Object, the set of possible types is open, so the default is required for the switch to be exhaustive; without it the code does not compile.
3Guards With when
The when keyword adds a boolean condition, called a guard, to a pattern. The case matches only if the pattern matches and the guard is true. The guard can use the binding, here s, because it runs only after the type test succeeded. If the guard is false, matching simply continues with the next case, which is why a String of six characters falls through to case String s and returns short string.
Guards keep the conditions next to the type they belong to, instead of nesting an if inside the case body. During the preview releases, guards were written with && instead of when; Java 21 settled on when, so code from Java 17 or 19 previews will not compile unchanged.
4Why case null Matters
Traditionally, switch throws NullPointerException when the selector is null, and that is still the behaviour unless the switch has a case null. Even default does not match null; it only covers non-null values that no other case matched.
The reason for this design is backward compatibility: existing switches that relied on throwing for null keep doing so, and new code opts in explicitly. So whenever the selector might be null and we want an answer rather than an exception, we write case null, either alone or combined as case null, default.
5Order and Dominance
Because the first matching case wins, a general pattern placed before a more specific one would make the specific case unreachable. The compiler detects this and reports it as an error: the later case label is dominated by the earlier one.
An unguarded pattern dominates any later pattern for the same type or a subtype, guarded or not. A guarded pattern does not dominate an unguarded one, because the guard might be false, so the correct order is always specific and guarded cases first, then the general case for the same type. Similarly, default must not come before cases it would cover in a way that makes them unreachable. These checks turn ordering mistakes, which an if-chain would hide, into compile errors.
6Follow-up questions
What happens if we leave out default in this example?
The switch is not exhaustive, because an Object could be any type, so the compiler reports an error for a switch expression. Exhaustiveness without default is only possible when the selector's type is a sealed type or an enum whose permitted subtypes or constants are all covered.
Can we use primitive types like int in these patterns?
Not as a final feature in Java 25. Here obj is an Object, so 42 is boxed to Integer and matches case Integer i. Primitive type patterns are a preview feature in Java 25, so check your release before using them.
Is the switch slower than the if-chain?
No in practice. The compiler translates pattern switches using an invokedynamic-based type switch that can check types efficiently, and the result is at least comparable to a hand-written chain. Choose it for clarity and compile-time checks.
7Conclusion
In this answer, we replaced an if-instanceof chain with a pattern switch: case null returns "null", a guarded case String s when s.length() > 10 returns the length, a plain String case returns "short string", Integer returns "int" and default returns "other". We saw that when adds a guard, that without case null the switch throws NullPointerException, that default does not cover null, and that a general pattern before a specific one is a dominance compile error. The feature is final since Java 21 through JEP 441.
Open with
I would write return switch on obj, with case null arrow "null", then case String s when s.length() greater than 10 arrow "long " plus the length, then case String s arrow "short string", case Integer i arrow "int", and default arrow "other".
Then, if they want more
Each case is a type pattern that both checks the type and binds the value, and the first matching case wins. The when keyword adds a guard, a condition on the bound value; if it is false, matching just continues with the next case, so a short string falls through to the plain String case. A few rules matter here.
Without case null, a switch still throws NullPointerException for a null selector, and default does not cover null, so I add case null, or case null, default if both should behave the same.
Order matters too: if I put the plain String case before the guarded one, the compiler reports that the guarded case is dominated, because it could never be reached. A guarded case does not dominate an unguarded one, so specific and guarded cases always go first.
Since obj is an Object, the default is required for the switch expression to be exhaustive; with a sealed type I could leave it out. And the arrow form never falls through, so there is no break to forget. Pattern matching for switch was finalized in Java 21 with JEP 441.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Java 21, Java 25, Java 17
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Java Language Specification, Java SE 21, Java SE 21 API documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a switch that returns a description for an Object: "null" for null, the length for...": https://scrivio-interview-library.netlify.app/java/sealed-and-pattern-matching/29d36502ac/