Java 17: Exhaustive switch over a sealed type

With sealed types the compiler knows all cases, so no default is needed.

Code
sealed interface Msg permits Text, Ping {}
record Text(String body) implements Msg {}
record Ping() implements Msg {}

Msg m = new Text("hi");
String out = switch (m) {
    case Text t -> "text: " + t.body();
    case Ping p -> "ping";
};
System.out.println(out);
Output
text: hi
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-07-26