Patterns in switch

A switch case may name a type instead of a constant, and then it matches every value of that type, like an instanceof with a branch. The selector may be an Object, the cases are tried in order, and the compiler still insists on exhaustiveness for a switch that produces a value. This is the final form in Java 21.

Type patterns in a switch

The four values below are an Integer, a String, a Double and null. Each case names the type it accepts and binds the value to a name of that type; a default catches the rest:

public class TypeSwitch { public static void main(String[] args) { Object[] values = {1, "two", 3.0, null}; for (Object value : values) { System.out.println(describe(value)); } } static String describe(Object value) { return switch (value) { case Integer n -> "int " + n; case String s -> "string of " + s.length(); case null -> "null"; default -> "other"; }; } }

javac -Xlint:all TypeSwitch.java
java TypeSwitch

int 1
string of 3
other
null

The old form of this method is an if chain with three instanceof tests, and before Java 21 the null value threw a NullPointerException at the switch itself. The selector may be null now, and the case decides what that means.

null as a label

case null matches a null selector, and it may be joined with default when both answer the same thing. A switch that names neither still throws for null, which is the old behaviour kept on purpose:

public class NullDefault { public static void main(String[] args) { Object[] values = {null, 42}; for (Object value : values) { System.out.println(describe(value)); } } static String describe(Object value) { return switch (value) { case Integer n -> "int " + n; case null, default -> "not an int"; }; } }

javac -Xlint:all NullDefault.java
java NullDefault

not an int
int 42

case null, default is one label with two ways in, and it keeps the branch count down. A null alone would also work, and then the default would still be needed for every other type.

Exhaustiveness

A switch expression must produce a value on every path, so the compiler checks that the cases cover every possible selector. Over an Object that means a default, because any type is possible. Without one the build stops at the switch keyword:

public class NonExhaustive { public static void main(String[] args) { System.out.println(describe(1)); } static String describe(Object value) { return switch (value) { case Integer n -> "int " + n; case String s -> "string " + s; }; } }

javac -Xlint:all NonExhaustive.java

NonExhaustive.java:7: error: the switch expression does not cover all possible input values
return switch (value) {
^
1 error

The message does not say which value is missing, and over a sealed interface it is often the same line: the check is exact there, because the permitted list is known, but the wording does not enumerate what is absent. What changes with a sealed type is that the check can succeed at all without a default; the next section and lesson 061 show that form.

A dominated case

The cases are tried in order, so a case that a previous case already accepts can never run. The compiler reports it instead of leaving dead code in the program:

public class Dominated { public static void main(String[] args) { System.out.println(describe(1)); } static String describe(Number value) { return switch (value) { case Number n -> "number " + n; case Integer i -> "int " + i; }; } }

javac -Xlint:all Dominated.java

Dominated.java:9: error: this case label is dominated by a preceding case label
case Integer i -> "int " + i;
^
1 error

An Integer is a Number, so the first case already took it. The fix is to put the narrower case first, which is the same rule a chain of instanceof tests follows in lesson 059, and the compiler enforces it rather than trusting the order.

A switch over a sealed type

Over a sealed interface those two errors become the useful ones: a missing subtype is named, and no default is needed. Lesson 058 built the hierarchy and lesson 061 builds a whole model on it; the shape here is the shortest form of the same idea, with a guard that labels a zero radius:

public class Shapes { public static void main(String[] args) { Shape[] shapes = {new Circle(0), new Circle(2), new Square(3)}; for (Shape shape : shapes) { System.out.println(describe(shape)); } } static String describe(Shape shape) { return switch (shape) { case Circle(double r) when r == 0 -> "a point"; case Circle(double r) -> String.format("circle %.1f", r); case Square(double s) -> String.format("square %.1f", s); }; } } sealed interface Shape permits Circle, Square { } record Circle(double radius) implements Shape { } record Square(double side) implements Shape { }

javac -Xlint:all Shapes.java
java Shapes

a point
circle 2.0
square 3.0

Two cases name Circle and the first has a guard, which is allowed because the second is broader and still reachable: the guard is part of the label, so the dominance rule sees two different labels. The Square case completes the permitted list, and the switch needs nothing else.

Exercises

  1. Add a Boolean case to TypeSwitch before the null case and print a value of each type.
  2. Remove the default from TypeSwitch and read the error.
  3. Reverse the two cases of Dominated and run it.
  4. Add a Triangle to Shapes and make the switch compile again.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which label matches every value of a type?

    Answer

    A type pattern, as case Integer n

    A type pattern tests the runtime type and binds the value, like instanceof.

  2. What does case null, default mean?

    Answer

    One branch for a null selector and for every value the other cases do not match

    The two labels share a body, which is allowed when they answer the same thing.

  3. When is a case label dominated?

    Answer

    When a preceding case already matches every value it would match

    The cases are tried in order, so a narrower label after a broader one can never run.

  4. What does this program print? public class Q1 { public static void main(String[] args) { Object o = "abc"; System.out.println(describe(o)); } static String describe(Object o) { return switch (o) { case Integer n -> "int"; case String s -> "string " + s.length(); default -> "other"; }; } }

    Answer

    string 3

    The value is a String and the case binds it, so its length is printed.

  5. What does this program print? public class Q2 { public static void main(String[] args) { System.out.println(describe(null)); } static String describe(Object o) { return switch (o) { case Integer n -> "int"; case null -> "null"; default -> "other"; }; } }

    Answer

    null

    The null case matches the null selector and answers for it.

  6. What is the first line of the compiler output for this program? public class Q3 { public static void main(String[] args) { System.out.println(describe(1)); } static String describe(Object o) { return switch (o) { case Integer n -> "int"; case String s -> "string"; }; } }

    Answer

    error: the switch expression does not cover all possible input values

    Over Object the two cases are not exhaustive, so a default is required.

  7. What is the first line of the compiler output for this program? public class Q4 { public static void main(String[] args) { System.out.println(describe(1)); } static String describe(Number n) { return switch (n) { case Number x -> "number"; case Integer i -> "int"; }; } }

    Answer

    error: this case label is dominated by a preceding case label

    Every Integer is a Number, so the second case can never be chosen.

  8. What does this program print? public class Q5 { public static void main(String[] args) { System.out.println(kind(new C(0))); System.out.println(kind(new C(2))); } static String kind(S s) { return switch (s) { case C(int r) when r == 0 -> "zero"; case C(int r) -> "circle"; }; } } sealed interface S permits C { } record C(int r) implements S { }

    Answer

    zero then circle

    The guard accepts the zero radius, and the unguarded case takes the other one.

  9. What happens to a null selector in a switch with no null case and no default?

    Answer

    It throws NullPointerException at run time

    The old null behaviour is kept unless a case names null or the default covers it.

  10. Why does a switch over a sealed interface need no default?

    Answer

    The permitted subtypes are known and the cases cover them all

    Exhaustiveness is checked against the sealed list, and a missing subtype is an error.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev