liveBook · Manning

Exhaustive switch statement

As explained in 100 Java Mistakes and How to Avoid Them

An exhaustive switch statement is a Java switch statement whose cases cover every permitted value or subtype in its selector domain.

An exhaustive switch statement handles every permitted subtype in a sealed selector hierarchy. The compiler then rejects the switch when a new permitted subtype is not handled. section 8.2

Processing every Entry subtype

sealed interface Entry {} record IntEntry(int value) implements Entry {} record StringEntry(String value) implements Entry {} void processList(List<Entry> list) { for (Entry element : list) { switch (element) { case IntEntry(int number) -> processNumber(number); case StringEntry(String string) -> processString(string); } } } If another permitted Entry subtype is added, compilation fails at this switch until its case is handled. section 8.2

sealed interface Entry {}
record IntEntry(int value) implements Entry {}
record StringEntry(String value) implements Entry {}

void processList(List<Entry> list) {
  for (Entry element : list) {
    switch (element) {
      case IntEntry(int number) -> processNumber(number);
      case StringEntry(String string) -> processString(string);
    }
  }
}

Inspect the compact sealed hierarchy and pattern cases used to process list elements. section 8.2

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains the pattern and its compile-time consequence, without detailing broader switch semantics or compiler internals.
Examples
Demonstrates IntEntry and StringEntry records processed through a switch over Entry values.
What it assumes
Assumes familiarity with Java interfaces, records, sealed types, and pattern matching.
What you can do after
Build it from scratch by declaring a sealed hierarchy and covering its permitted record subtypes in a switch.
How it connects
Connects sealed type hierarchies with records, deconstruction patterns, and subtype processing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.